使用Java High Level REST Client操作elasticsearch

Java高级别REST客户端(The Java High Level REST Client)以后简称高级客户端,内部仍然是基于低级客户端。它提供了更多的API,接受请求对象作为参数并返回响应对象,由客户端自己处理编码和解码。

每个API都可以同步或异步调用。 同步方法返回一个响应对象,而异步方法的名称以async后缀结尾,需要一个监听器参数,一旦收到响应或错误,就会被通知(由低级客户端管理的线程池)。

高级客户端依赖于Elasticsearch core项目。 它接受与TransportClient相同的请求参数并返回相同的响应对象。

兼容性

高级客户端需要Java 1.8并依赖于Elasticsearch core项目。 客户端版本需要与Elasticsearch版本相同。 它与TransportClient请求的参数和返回响应对象相同。 如果您需要将应用程序从TransportClient迁移到新的REST客户端,请参阅“迁移指南”。

要能够与Elasticsearch进行通信,主版本号需要一致,次版本号不必相同,因为它是向前兼容的。次版本号小于等于elasticsearch的都可以。这意味着它支持与更高版本的Elasticsearch进行通信。

6.0客户端能够与任何6.x Elasticsearch节点通信,而6.1客户端肯定能够与6.1,6.2和任何后来的6.x版本进行通信,但与旧版本的Elasticsearch节点通信时可能会存在不兼容的问题,例如6.1和6.0之间,可能6.1客户端支持elasticsearch 6.0还没出来的API。

建议在将Elasticsearch集群升级到新的主要版本时升级高级客户端,因为REST API中断更改可能会导致意料之外的结果,具体取决于请求所击中的节点,以及新添加的API只能被更新的客户端版本支持。应该在群集中的所有节点都升级到新的主要版本之后,客户端才更新。

可以在这里找到高级客户端的Javadoc。

Maven 仓库

高级客户端托管在Maven Central上。所需的最低Java版本是1.8。高级客户端与Elasticsearch的发布周期相同。

Maven配置

下面是使用maven作为依赖管理器配置依赖项。 将以下内容添加到您的pom.xml文件中:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.2.3</version>
</dependency>

Gradle 配置

下面是使用gradle作为依赖项管理器来配置依赖项。在您的build.gradle中添加以下内容:

dependencies {
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:6.2.3'
}

Lucene Snapshot repository
任何主要版本(像beta版)的第一个版本可能都是在Lucene Snapshot版本之上构建的。在这种情况下,您将无法解析客户端的Lucene依赖关系。

例如,如果您想使用依赖于Lucene 7.0.0-snapshot-00142c9的6.0.0-beta1版本,您必须定义以下repository。

Maven:

复制代码
<repository>
    <id>elastic-lucene-snapshots</id>
    <name>Elastic Lucene Snapshots</name>
    <url>http://s3.amazonaws.com/download.elasticsearch.org/lucenesnapshots/00142c9</url>
    <releases><enabled>true</enabled></releases>
    <snapshots><enabled>false</enabled></snapshots>
</repository>
复制代码

Gradle

maven {
    url 'http://s3.amazonaws.com/download.elasticsearch.org/lucenesnapshots/00142c9'
}

Dependencies

高级客户端依赖于以下部件及其传递依赖关系:

  • org.elasticsearch.client:elasticsearch-rest-client
  • org.elasticsearch:elasticsearch

初始化

RestHighLevelClient实例需要低级客户端构建器来构建,如下所示:

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

高级客户端将在内部创建低级客户端,用来执行基于提供的构建器的请求,并管理其生命周期。
当不再需要时,需要关闭高级客户端实例,以便它所使用的所有资源以及底层的http客户端实例及其线程得到正确释放。可以通过close方法来完成,该方法将关闭内部的RestClient实例。

client.close();

在有关高级客户端的其他文档中,RestHighLevelClient实例将使用client来代替。

支持的API

Indices APIs

Create Index API

复制代码
RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    CreateIndexRequest request </span>= <span style="color: #0000ff;">new</span> CreateIndexRequest("twitter_two");<span style="color: #008000;">//</span><span style="color: #008000;">创建索引</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">创建的每个索引都可以有与之关联的特定设置。</span>

request.settings(Settings.builder()
.put(
"index.number_of_shards", 3)
.put(
"index.number_of_replicas", 2)
);
//创建索引时创建文档类型映射
request.mapping("tweet",//类型定义
" { " +
" "tweet": { " +
" "properties": { " +
" "message": { " +
" "type": "text" " +
" } " +
" } " +
" } " +
" }",//类型映射,需要的是一个JSON字符串
XContentType.JSON);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">为索引设置一个别名</span>

request.alias(
new Alias("twitter_alias")
);
//可选参数
request.timeout(TimeValue.timeValueMinutes(2));//超时,等待所有节点被确认(使用TimeValue方式)
//request.timeout("2m");//超时,等待所有节点被确认(使用字符串方式)

request.masterNodeTimeout(TimeValue.timeValueMinutes(
1));//连接master节点的超时时间(使用TimeValue方式)
//request.masterNodeTimeout("1m");//连接master节点的超时时间(使用字符串方式)

request.waitForActiveShards(
2);//在创建索引API返回响应之前等待的活动分片副本的数量,以int形式表示。
//request.waitForActiveShards(ActiveShardCount.DEFAULT);//在创建索引API返回响应之前等待的活动分片副本的数量,以ActiveShardCount形式表示。

    <span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    CreateIndexResponse createIndexResponse =<span style="color: #000000;"> client.indices().create(request);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步执行</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">异步执行创建索引请求需要将CreateIndexRequest实例和ActionListener实例传递给异步方法:</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">CreateIndexResponse的典型监听器如下所示:</span>
    <span style="color: #008000;">//</span><span style="color: #008000;">异步方法不会阻塞并立即返回。</span>
    ActionListener&lt;CreateIndexResponse&gt; listener = <span style="color: #0000ff;">new</span> ActionListener&lt;CreateIndexResponse&gt;<span style="color: #000000;">() {
        @Override
        public </span><span style="color: #0000ff;">void</span><span style="color: #000000;"> onResponse(CreateIndexResponse createIndexResponse) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">如果执行成功,则调用onResponse方法;</span>

}
@Override
public
void onFailure(Exception e) {
//如果失败,则调用onFailure方法。
}
};
client.indices().createAsync(request, listener);
//要执行的CreateIndexRequest和执行完成时要使用的ActionListener

    <span style="color: #008000;">//</span><span style="color: #008000;">返回的CreateIndexResponse允许检索有关执行的操作的信息,如下所示:</span>
    <span style="color: #0000ff;">boolean</span> acknowledged = createIndexResponse.isAcknowledged();<span style="color: #008000;">//</span><span style="color: #008000;">指示是否所有节点都已确认请求</span>
    <span style="color: #0000ff;">boolean</span> shardsAcknowledged = createIndexResponse.isShardsAcknowledged();<span style="color: #008000;">//</span><span style="color: #008000;">指示是否在超时之前为索引中的每个分片启动了必需的分片副本数</span></pre>
复制代码

Delete Index API

复制代码
 RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    DeleteIndexRequest request </span>= <span style="color: #0000ff;">new</span> DeleteIndexRequest("twitter_two");<span style="color: #008000;">//</span><span style="color: #008000;">指定要删除的索引名称
    </span><span style="color: #008000;">//</span><span style="color: #008000;">可选参数:</span>
    request.timeout(TimeValue.timeValueMinutes(2)); <span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引删除(使用TimeValue形式)
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> request.timeout("2m"); </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引删除(使用字符串形式)</span>
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));////连接master节点的超时时间(使用TimeValue方式) // request.masterNodeTimeout("1m");//连接master节点的超时时间(使用字符串方式)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置IndicesOptions控制如何解决不可用的索引以及如何扩展通配符表达式</span>

request.indicesOptions(IndicesOptions.lenientExpandOpen());

    </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    DeleteIndexResponse deleteIndexResponse =<span style="color: #000000;"> client.indices().delete(request);

/* //异步执行删除索引请求需要将DeleteIndexRequest实例和ActionListener实例传递给异步方法:
//DeleteIndexResponse的典型监听器如下所示:
//异步方法不会阻塞并立即返回。
ActionListener<DeleteIndexResponse> listener = new ActionListener<DeleteIndexResponse>() {
@Override
public void onResponse(DeleteIndexResponse deleteIndexResponse) {
//如果执行成功,则调用onResponse方法;
}

        @Override
        public void onFailure(Exception e) {
            //如果失败,则调用onFailure方法。
        }
    };
    client.indices().deleteAsync(request, listener);</span><span style="color: #008000;">*/</span>

    <span style="color: #008000;">//</span><span style="color: #008000;">Delete Index Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的DeleteIndexResponse允许检索有关执行的操作的信息,如下所示:</span>
    <span style="color: #0000ff;">boolean</span> acknowledged = deleteIndexResponse.isAcknowledged();<span style="color: #008000;">//</span><span style="color: #008000;">是否所有节点都已确认请求


    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果找不到索引,则会抛出ElasticsearchException:</span>
    <span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        request </span>= <span style="color: #0000ff;">new</span> DeleteIndexRequest("does_not_exist"<span style="color: #000000;">);
        client.indices().delete(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (ElasticsearchException exception) {
        </span><span style="color: #0000ff;">if</span> (exception.status() ==<span style="color: #000000;"> RestStatus.NOT_FOUND) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">如果没有找到要删除的索引,要执行某些操作</span>

}
}

复制代码

Open Index API

复制代码
  RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    OpenIndexRequest request </span>= <span style="color: #0000ff;">new</span> OpenIndexRequest("twitter");<span style="color: #008000;">//</span><span style="color: #008000;">打开索引
    </span><span style="color: #008000;">//</span><span style="color: #008000;">可选参数:</span>
    request.timeout(TimeValue.timeValueMinutes(2)); <span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引已打开(使用TimeValue形式)
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> request.timeout("2m"); </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引已打开(使用字符串形式)</span>
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));////连接master节点的超时时间(使用TimeValue方式) // request.masterNodeTimeout("1m");//连接master节点的超时时间(使用字符串方式) request.waitForActiveShards(2);//在打开索引API返回响应之前等待的活动分片副本的数量,以int形式表示。 //request.waitForActiveShards(ActiveShardCount.ONE);//在打开索引API返回响应之前等待的活动分片副本的数量,以ActiveShardCount形式表示。
    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置IndicesOptions控制如何解决不可用的索引以及如何扩展通配符表达式</span>

request.indicesOptions(IndicesOptions.strictExpandOpen());

    </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    OpenIndexResponse openIndexResponse =<span style="color: #000000;"> client.indices().open(request);

    </span><span style="color: #008000;">/*</span><span style="color: #008000;">//异步执行打开索引请求需要将OpenIndexRequest实例和ActionListener实例传递给异步方法:
    //OpenIndexResponse的典型监听器如下所示:
    //异步方法不会阻塞并立即返回。
    ActionListener&lt;OpenIndexResponse&gt; listener = new ActionListener&lt;OpenIndexResponse&gt;() {
        @Override
        public void onResponse(OpenIndexResponse openIndexResponse) {
            //如果执行成功,则调用onResponse方法;
        }

        @Override
        public void onFailure(Exception e) {
            //如果失败,则调用onFailure方法。
        }
    };
    client.indices().openAsync(request, listener);</span><span style="color: #008000;">*/</span>

    <span style="color: #008000;">//</span><span style="color: #008000;">Open Index Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的OpenIndexResponse允许检索有关执行的操作的信息,如下所示:</span>
    <span style="color: #0000ff;">boolean</span> acknowledged = openIndexResponse.isAcknowledged();<span style="color: #008000;">//</span><span style="color: #008000;">指示是否所有节点都已确认请求</span>
    <span style="color: #0000ff;">boolean</span> shardsAcknowledged = openIndexResponse.isShardsAcknowledged();<span style="color: #008000;">//</span><span style="color: #008000;">指示是否在超时之前为索引中的每个分片启动了必需的分片副本数</span></pre>
复制代码

Close Index API

复制代码
 RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
        CloseIndexRequest request = new CloseIndexRequest("index");//关闭索引
    </span><span style="color: #008000;">//</span><span style="color: #008000;">可选参数:</span>
    request.timeout(TimeValue.timeValueMinutes(2)); <span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引已关闭(使用TimeValue形式)
    </span><span style="color: #008000;">//</span><span style="color: #008000;"> request.timeout("2m"); </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时,等待所有节点确认索引已关闭(使用字符串形式)</span>
request.masterNodeTimeout(TimeValue.timeValueMinutes(1));////连接master节点的超时时间(使用TimeValue方式) // request.masterNodeTimeout("1m");//连接master节点的超时时间(使用字符串方式)
    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置IndicesOptions控制如何解决不可用的索引以及如何扩展通配符表达式</span>

request.indicesOptions(IndicesOptions.lenientExpandOpen());
//同步执行
CloseIndexResponse closeIndexResponse = client.indices().close(request);

     </span><span style="color: #008000;">/*</span><span style="color: #008000;">//异步执行打开索引请求需要将CloseIndexRequest实例和ActionListener实例传递给异步方法:
    //CloseIndexResponse的典型监听器如下所示:
    //异步方法不会阻塞并立即返回。
    ActionListener&lt;CloseIndexResponse&gt; listener = new ActionListener&lt;CloseIndexResponse&gt;() {
        @Override
        public void onResponse(CloseIndexResponse closeIndexResponse) {
             //如果执行成功,则调用onResponse方法;
        }

        @Override
        public void onFailure(Exception e) {
             //如果失败,则调用onFailure方法。
        }
    };
    client.indices().closeAsync(request, listener); </span><span style="color: #008000;">*/</span>

    <span style="color: #008000;">//</span><span style="color: #008000;">Close Index Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的CloseIndexResponse 允许检索有关执行的操作的信息,如下所示:</span>
    <span style="color: #0000ff;">boolean</span> acknowledged = closeIndexResponse.isAcknowledged(); <span style="color: #008000;">//</span><span style="color: #008000;">指示是否所有节点都已确认请求</span></pre>
复制代码

Single document APIs

Index API

复制代码
RestHighLevelClient client = new RestHighLevelClient(
               RestClient.builder(
                       new HttpHost("localhost", 9200, "http"),
                       new HttpHost("localhost", 9201, "http")));
       IndexRequest indexRequest1 = new IndexRequest(
               "posts",//索引名称
               "doc",//类型名称
               "1");//文档ID
   </span><span style="color: #008000;">//</span><span style="color: #008000;">==============================提供文档源========================================
   </span><span style="color: #008000;">//</span><span style="color: #008000;">方式1:以字符串形式提供</span>
   String jsonString = "{" +
           ""user":"kimchy"," +
           ""postDate":"2013-01-30"," +
           ""message":"trying out Elasticsearch"" +
           "}"<span style="color: #000000;">;
   indexRequest1.source(jsonString, XContentType.JSON);

   </span><span style="color: #008000;">//</span><span style="color: #008000;">方式2:以Map形式提供</span>
   Map&lt;String, Object&gt; jsonMap = <span style="color: #0000ff;">new</span> HashMap&lt;&gt;<span style="color: #000000;">();
   jsonMap.put(</span>"user", "kimchy"<span style="color: #000000;">);
   jsonMap.put(</span>"postDate", <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date());
   jsonMap.put(</span>"message", "trying out Elasticsearch"<span style="color: #000000;">);
   </span><span style="color: #008000;">//</span><span style="color: #008000;">Map会自动转换为JSON格式的文档源</span>
   IndexRequest indexRequest2 = <span style="color: #0000ff;">new</span> IndexRequest("posts", "doc", "1"<span style="color: #000000;">)
           .source(jsonMap);

   </span><span style="color: #008000;">//</span><span style="color: #008000;"> 方式3:文档源以XContentBuilder对象的形式提供,Elasticsearch内部会帮我们生成JSON内容</span>
XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.field("user", "kimchy"); builder.field("postDate", new Date()); builder.field("message", "trying out Elasticsearch"); } builder.endObject(); IndexRequest indexRequest3 = new IndexRequest("posts", "doc", "1") .source(builder);
   </span><span style="color: #008000;">//</span><span style="color: #008000;">方式4:以Object key-pairs提供的文档源,它会被转换为JSON格式</span>
   IndexRequest indexRequest4 = <span style="color: #0000ff;">new</span> IndexRequest("posts", "doc", "1"<span style="color: #000000;">)
    .source(</span>"user", "kimchy"<span style="color: #000000;">,
           </span>"postDate", <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date(),
           </span>"message", "trying out Elasticsearch"<span style="color: #000000;">);

   </span><span style="color: #008000;">//</span><span style="color: #008000;">===============================可选参数start====================================</span>
   indexRequest1.routing("routing");<span style="color: #008000;">//</span><span style="color: #008000;">设置路由值</span>
   indexRequest1.parent("parent");<span style="color: #008000;">//</span><span style="color: #008000;">设置parent值

   </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时:等待主分片变得可用的时间</span>
   indexRequest1.timeout(TimeValue.timeValueSeconds(1));<span style="color: #008000;">//</span><span style="color: #008000;">TimeValue方式</span>
   indexRequest1.timeout("1s");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式

   </span><span style="color: #008000;">//</span><span style="color: #008000;">刷新策略</span>
   indexRequest1.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);<span style="color: #008000;">//</span><span style="color: #008000;">WriteRequest.RefreshPolicy实例方式</span>
   indexRequest1.setRefreshPolicy("wait_for");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式</span>
indexRequest1.version(2);//设置版本 indexRequest1.versionType(VersionType.EXTERNAL);//设置版本类型
   </span><span style="color: #008000;">//</span><span style="color: #008000;">操作类型</span>
   indexRequest1.opType(DocWriteRequest.OpType.CREATE);<span style="color: #008000;">//</span><span style="color: #008000;">DocWriteRequest.OpType方式</span>
   indexRequest1.opType("create");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式, 可以是 create 或 update (默认)

   </span><span style="color: #008000;">//</span><span style="color: #008000;">The name of the ingest pipeline to be executed before indexing the document</span>
   indexRequest1.setPipeline("pipeline"<span style="color: #000000;">);
   
   </span><span style="color: #008000;">//</span><span style="color: #008000;">===============================执行====================================
   </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
   IndexResponse indexResponse =<span style="color: #000000;"> client.index(indexRequest1);

   </span><span style="color: #008000;">//</span><span style="color: #008000;">异步执行
   </span><span style="color: #008000;">//</span><span style="color: #008000;">IndexResponse 的典型监听器如下所示:
   </span><span style="color: #008000;">//</span><span style="color: #008000;">异步方法不会阻塞并立即返回。</span>
   ActionListener&lt;IndexResponse&gt; listener = <span style="color: #0000ff;">new</span> ActionListener&lt;IndexResponse&gt;<span style="color: #000000;">() {
       @Override
       </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onResponse(IndexResponse indexResponse) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">执行成功时调用。 Response以参数方式提供</span>

}

       @Override
       </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onFailure(Exception e) {
           </span><span style="color: #008000;">//</span><span style="color: #008000;">在失败的情况下调用。 引发的异常以参数方式提供</span>

}
};
//异步执行索引请求需要将IndexRequest实例和ActionListener实例传递给异步方法:
client.indexAsync(indexRequest2, listener);

   </span><span style="color: #008000;">//</span><span style="color: #008000;">Index Response
   </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的IndexResponse允许检索有关执行操作的信息,如下所示:</span>
   String index =<span style="color: #000000;"> indexResponse.getIndex();
   String type </span>=<span style="color: #000000;"> indexResponse.getType();
   String id </span>=<span style="color: #000000;"> indexResponse.getId();
   </span><span style="color: #0000ff;">long</span> version =<span style="color: #000000;"> indexResponse.getVersion();
   </span><span style="color: #0000ff;">if</span> (indexResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.CREATED) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理(如果需要)第一次创建文档的情况</span>
   } <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (indexResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.UPDATED) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理(如果需要)文档被重写的情况</span>

}
ReplicationResponse.ShardInfo shardInfo
= indexResponse.getShardInfo();
if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
//处理成功分片数量少于总分片数量的情况
}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason
= failure.reason();//处理潜在的失败
}
}

   </span><span style="color: #008000;">//</span><span style="color: #008000;">如果存在版本冲突,则会抛出ElasticsearchException:</span>
   IndexRequest request = <span style="color: #0000ff;">new</span> IndexRequest("posts", "doc", "1"<span style="color: #000000;">)
           .source(</span>"field", "value"<span style="color: #000000;">)
           .version(</span>1<span style="color: #000000;">);
   </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
       IndexResponse response </span>=<span style="color: #000000;"> client.index(request);
   } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(ElasticsearchException e) {
       </span><span style="color: #0000ff;">if</span> (e.status() ==<span style="color: #000000;"> RestStatus.CONFLICT) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">引发的异常表示返回了版本冲突错误</span>

}
}

   </span><span style="color: #008000;">//</span><span style="color: #008000;">如果opType设置为创建但是具有相同索引,类型和ID的文档已存在,则也会发生同样的情况:</span>
   request = <span style="color: #0000ff;">new</span> IndexRequest("posts", "doc", "1"<span style="color: #000000;">)
           .source(</span>"field", "value"<span style="color: #000000;">)
           .opType(DocWriteRequest.OpType.CREATE);
   </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
       IndexResponse response </span>=<span style="color: #000000;"> client.index(request);
   } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(ElasticsearchException e) {
       </span><span style="color: #0000ff;">if</span> (e.status() ==<span style="color: #000000;"> RestStatus.CONFLICT) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">引发的异常表示返回了版本冲突错误</span>

}
}

复制代码

Get API

复制代码
RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    GetRequest getRequest </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> GetRequest(
            </span>"posts",<span style="color: #008000;">//</span><span style="color: #008000;">索引</span>
            "doc",<span style="color: #008000;">//</span><span style="color: #008000;">类型</span>
            "1");<span style="color: #008000;">//</span><span style="color: #008000;">文档ID

    </span><span style="color: #008000;">//</span><span style="color: #008000;">===============================可选参数start====================================
    </span><span style="color: #008000;">//</span><span style="color: #008000;">禁用_source检索,默认为启用</span>
    getRequest.fetchSourceContext(<span style="color: #0000ff;">new</span> FetchSourceContext(<span style="color: #0000ff;">false</span><span style="color: #000000;">));


    </span><span style="color: #008000;">//</span><span style="color: #008000;">为特定字段配置_source_include</span>
    String[] includes = <span style="color: #0000ff;">new</span> String[]{"message", "*Date"<span style="color: #000000;">};
    String[] excludes </span>=<span style="color: #000000;"> Strings.EMPTY_ARRAY;
    FetchSourceContext fetchSourceContext </span>= <span style="color: #0000ff;">new</span> FetchSourceContext(<span style="color: #0000ff;">true</span><span style="color: #000000;">, includes, excludes);
    getRequest.fetchSourceContext(fetchSourceContext);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">为指定字段配置_source_exclude</span>
    String[] includes1 =<span style="color: #000000;"> Strings.EMPTY_ARRAY;
    String[] excludes1 </span>= <span style="color: #0000ff;">new</span> String[]{"message"<span style="color: #000000;">};
    FetchSourceContext fetchSourceContext1 </span>= <span style="color: #0000ff;">new</span> FetchSourceContext(<span style="color: #0000ff;">true</span><span style="color: #000000;">, includes, excludes);
    getRequest.fetchSourceContext(fetchSourceContext);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">配置指定stored_fields的检索(要求字段在映射中单独存储)</span>
    getRequest.storedFields("message"<span style="color: #000000;">);
    GetResponse getResponse </span>=<span style="color: #000000;"> client.get(getRequest);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">检索message 存储字段(要求将字段分开存储在映射中)</span>
    String message = getResponse.getField("message"<span style="color: #000000;">).getValue();

    getRequest.routing(</span>"routing");<span style="color: #008000;">//</span><span style="color: #008000;">设置routing值</span>
    getRequest.parent("parent");<span style="color: #008000;">//</span><span style="color: #008000;">设置parent值</span>
    getRequest.preference("preference");<span style="color: #008000;">//</span><span style="color: #008000;">设置preference值</span>
    getRequest.realtime(<span style="color: #0000ff;">false</span>);<span style="color: #008000;">//</span><span style="color: #008000;">设置realtime为false,默认是true</span>
    getRequest.refresh(<span style="color: #0000ff;">true</span>);<span style="color: #008000;">//</span><span style="color: #008000;">在检索文档之前执行刷新(默认为false)</span>
    getRequest.version(2);<span style="color: #008000;">//</span><span style="color: #008000;">设置版本</span>
    getRequest.versionType(VersionType.EXTERNAL);<span style="color: #008000;">//</span><span style="color: #008000;">设置版本类型
    </span><span style="color: #008000;">//</span><span style="color: #008000;">===============================可选参数end====================================

    </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    GetResponse getResponse1 =<span style="color: #000000;"> client.get(getRequest);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步执行
    </span><span style="color: #008000;">//</span><span style="color: #008000;">GetResponse 的典型监听器如下所示:
    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步方法不会阻塞并立即返回。</span>
    ActionListener&lt;GetResponse&gt; listener = <span style="color: #0000ff;">new</span> ActionListener&lt;GetResponse&gt;<span style="color: #000000;">() {
        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onResponse(GetResponse getResponse) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">执行成功时调用。 Response以参数方式提供</span>

}

        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onFailure(Exception e) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">在失败的情况下调用。 引发的异常以参数方式提供</span>

}
};
//异步执行获取索引请求需要将GetRequest 实例和ActionListener实例传递给异步方法:
client.getAsync(getRequest, listener);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">Get Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的GetResponse允许检索请求的文档及其元数据和最终存储的字段。</span>
    String index =<span style="color: #000000;"> getResponse.getIndex();
    String type </span>=<span style="color: #000000;"> getResponse.getType();
    String id </span>=<span style="color: #000000;"> getResponse.getId();
    </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (getResponse.isExists()) {
        </span><span style="color: #0000ff;">long</span> version =<span style="color: #000000;"> getResponse.getVersion();
        String sourceAsString </span>= getResponse.getSourceAsString();<span style="color: #008000;">//</span><span style="color: #008000;">检索文档(String形式)</span>
        Map&lt;String, Object&gt; sourceAsMap = getResponse.getSourceAsMap();<span style="color: #008000;">//</span><span style="color: #008000;">检索文档(Map&lt;String, Object&gt;形式)</span>
        <span style="color: #0000ff;">byte</span>[] sourceAsBytes = getResponse.getSourceAsBytes();<span style="color: #008000;">//</span><span style="color: #008000;">检索文档(byte[]形式)</span>
    } <span style="color: #0000ff;">else</span><span style="color: #000000;"> {
       </span><span style="color: #008000;">/*</span><span style="color: #008000;"> 处理找不到文档的情况。 请注意,尽管返回404状态码,
        但返回的是有效的GetResponse,而不是抛出的异常。
        此类Response不包含任何源文档,并且其isExists方法返回false。</span><span style="color: #008000;">*/</span><span style="color: #000000;">
    }


    </span><span style="color: #008000;">//</span><span style="color: #008000;">当针对不存在的索引执行获取请求时,响应404状态码,将引发ElasticsearchException,需要按如下方式处理:</span>
    GetRequest request = <span style="color: #0000ff;">new</span> GetRequest("does_not_exist", "doc", "1"<span style="color: #000000;">);
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        GetResponse getResponse2 </span>=<span style="color: #000000;"> client.get(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (ElasticsearchException e) {
        </span><span style="color: #0000ff;">if</span> (e.status() ==<span style="color: #000000;"> RestStatus.NOT_FOUND) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">处理因为索引不存在而抛出的异常情况</span>

}
}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果请求了特定的文档版本,并且现有文档具有不同的版本号,则会引发版本冲突:</span>
    <span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        GetRequest request1 </span>= <span style="color: #0000ff;">new</span> GetRequest("posts", "doc", "1").version(2<span style="color: #000000;">);
        GetResponse getResponse3 </span>=<span style="color: #000000;"> client.get(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (ElasticsearchException exception) {
        </span><span style="color: #0000ff;">if</span> (exception.status() ==<span style="color: #000000;"> RestStatus.CONFLICT) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">引发的异常表示返回了版本冲突错误</span>

}
}

复制代码

Delete API

复制代码
RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    DeleteRequest request </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> DeleteRequest (
            </span>"posts",<span style="color: #008000;">//</span><span style="color: #008000;">索引</span>
            "doc",<span style="color: #008000;">//</span><span style="color: #008000;">类型</span>
            "1");<span style="color: #008000;">//</span><span style="color: #008000;">文档ID

    </span><span style="color: #008000;">//</span><span style="color: #008000;">===============================可选参数====================================</span>
    request.routing("routing");<span style="color: #008000;">//</span><span style="color: #008000;">设置routing值</span>
    request.parent("parent");<span style="color: #008000;">//</span><span style="color: #008000;">设置parent值

    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时:等待主分片变得可用的时间</span>
    request.timeout(TimeValue.timeValueMinutes(2));<span style="color: #008000;">//</span><span style="color: #008000;">TimeValue方式</span>
    request.timeout("1s");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式

    </span><span style="color: #008000;">//</span><span style="color: #008000;">刷新策略</span>
    request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);<span style="color: #008000;">//</span><span style="color: #008000;">WriteRequest.RefreshPolicy实例方式</span>
    request.setRefreshPolicy("wait_for");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式</span>
request.version(2);//设置版本 request.versionType(VersionType.EXTERNAL);//设置版本类型
    </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    DeleteResponse deleteResponse =<span style="color: #000000;"> client.delete(request);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步执行
    </span><span style="color: #008000;">//</span><span style="color: #008000;">DeleteResponse  的典型监听器如下所示:
    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步方法不会阻塞并立即返回。</span>
    ActionListener&lt;DeleteResponse &gt; listener = <span style="color: #0000ff;">new</span> ActionListener&lt;DeleteResponse &gt;<span style="color: #000000;">() {
        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onResponse(DeleteResponse  getResponse) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">执行成功时调用。 Response以参数方式提供</span>

}

        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onFailure(Exception e) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">在失败的情况下调用。 引发的异常以参数方式提供</span>

}
};
//异步执行获取索引请求需要将DeleteRequest 实例和ActionListener实例传递给异步方法:
client.deleteAsync(request, listener);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">Delete Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的DeleteResponse允许检索有关执行操作的信息,如下所示:</span>
    String index =<span style="color: #000000;"> deleteResponse.getIndex();
    String type </span>=<span style="color: #000000;"> deleteResponse.getType();
    String id </span>=<span style="color: #000000;"> deleteResponse.getId();
    </span><span style="color: #0000ff;">long</span> version =<span style="color: #000000;"> deleteResponse.getVersion();
    ReplicationResponse.ShardInfo shardInfo </span>=<span style="color: #000000;"> deleteResponse.getShardInfo();
    </span><span style="color: #0000ff;">if</span> (shardInfo.getTotal() !=<span style="color: #000000;"> shardInfo.getSuccessful()) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理成功分片数量少于总分片数量的情况</span>

}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason
= failure.reason();//处理潜在的失败
}
}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">还可以检查文档是否被找到:</span>
    DeleteRequest request1 = <span style="color: #0000ff;">new</span> DeleteRequest("posts", "doc", "does_not_exist"<span style="color: #000000;">);
    DeleteResponse deleteResponse1 </span>=<span style="color: #000000;"> client.delete(request);
    </span><span style="color: #0000ff;">if</span> (deleteResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.NOT_FOUND) {
       </span><span style="color: #008000;">//</span><span style="color: #008000;">如果找不到要删除的文档,执行某些操作</span>

}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果存在版本冲突,则会抛出ElasticsearchException:</span>
    <span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        DeleteRequest request2 </span>= <span style="color: #0000ff;">new</span> DeleteRequest("posts", "doc", "1").version(2<span style="color: #000000;">);
        DeleteResponse deleteResponse2 </span>=<span style="color: #000000;"> client.delete(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (ElasticsearchException exception) {
        </span><span style="color: #0000ff;">if</span> (exception.status() ==<span style="color: #000000;"> RestStatus.CONFLICT) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">引发的异常表示返回了版本冲突错误</span>

}
}

复制代码

Update API

复制代码
RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
    UpdateRequest request </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> UpdateRequest  (
            </span>"test",<span style="color: #008000;">//</span><span style="color: #008000;">索引</span>
            "_doc",<span style="color: #008000;">//</span><span style="color: #008000;">类型</span>
            "1");<span style="color: #008000;">//</span><span style="color: #008000;">文档ID

    </span><span style="color: #008000;">//</span><span style="color: #008000;">更新API允许通过使用脚本或传递部分文档来更新现有文档。

    </span><span style="color: #008000;">//</span><span style="color: #008000;">使用脚本
    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式1:该脚本可以作为内联脚本提供:</span>
    Map&lt;String, Object&gt; parameters = singletonMap("count", 4);<span style="color: #008000;">//</span><span style="color: #008000;">脚本参数
    </span><span style="color: #008000;">//</span><span style="color: #008000;">使用painless语言和上面的参数创建一个内联脚本</span>
    Script inline = <span style="color: #0000ff;">new</span> Script(ScriptType.INLINE, "painless", "ctx._source.field += params.count"<span style="color: #000000;">, parameters);
    request.script(inline);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式2:引用名称为increment-field的脚本,改脚本定义的位置还没搞清楚。</span>
    Script stored =
            <span style="color: #0000ff;">new</span> Script(ScriptType.STORED, <span style="color: #0000ff;">null</span>, "increment-field"<span style="color: #000000;">, parameters);
    request.script(stored);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">只更新部分
    </span><span style="color: #008000;">//</span><span style="color: #008000;">更新部分文档时,更新的部分文档将与现有文档合并。

    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式1:使用字符串形式</span>
    UpdateRequest request1 = <span style="color: #0000ff;">new</span> UpdateRequest("posts", "doc", "1"<span style="color: #000000;">);
    String jsonString </span>= "{" +
            ""updated":"2017-01-01"," +
            ""reason":"daily update"" +
            "}"<span style="color: #000000;">;
    request1.doc(jsonString, XContentType.JSON);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式2:使用Map形式,会被自动转为json格式</span>
    Map&lt;String, Object&gt; jsonMap = <span style="color: #0000ff;">new</span> HashMap&lt;&gt;<span style="color: #000000;">();
    jsonMap.put(</span>"updated", <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date());
    jsonMap.put(</span>"reason", "daily update"<span style="color: #000000;">);
    UpdateRequest request2 </span>= <span style="color: #0000ff;">new</span> UpdateRequest("posts", "doc", "1"<span style="color: #000000;">)
            .doc(jsonMap);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式3:使用XContentBuilder形式</span>
    XContentBuilder builder =<span style="color: #000000;"> XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.field(</span>"updated", <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date());
        builder.field(</span>"reason", "daily update"<span style="color: #000000;">);
    }
    builder.endObject();
    UpdateRequest request3 </span>= <span style="color: #0000ff;">new</span> UpdateRequest("posts", "doc", "1"<span style="color: #000000;">)
            .doc(builder);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">方式4:使用Object key-pairs形式</span>
    UpdateRequest request4 = <span style="color: #0000ff;">new</span> UpdateRequest("posts", "doc", "1"<span style="color: #000000;">)
            .doc(</span>"updated", <span style="color: #0000ff;">new</span><span style="color: #000000;"> Date(),
                    </span>"reason", "daily update"<span style="color: #000000;">);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果文档尚不存在,则可以使用upsert方法定义一些将作为新文档插入的内容:
    </span><span style="color: #008000;">//</span><span style="color: #008000;">与部分文档更新类似,可以使用接受String,Map,XContentBuilder或Object key-pairs的方式来定义upsert文档的内容。</span>
    String jsonString1 = "{"created":"2017-01-01"}"<span style="color: #000000;">;
    request.upsert(jsonString1, XContentType.JSON);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">=========================可选参数===========================</span>
    request.routing("routing");<span style="color: #008000;">//</span><span style="color: #008000;">设置routing值</span>
    request.parent("parent");<span style="color: #008000;">//</span><span style="color: #008000;">设置parent值

    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置超时:等待主分片变得可用的时间</span>
    request.timeout(TimeValue.timeValueSeconds(1));<span style="color: #008000;">//</span><span style="color: #008000;">TimeValue方式</span>
    request.timeout("1s");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式

    </span><span style="color: #008000;">//</span><span style="color: #008000;">刷新策略</span>
    request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);<span style="color: #008000;">//</span><span style="color: #008000;">WriteRequest.RefreshPolicy实例方式</span>
    request.setRefreshPolicy("wait_for");<span style="color: #008000;">//</span><span style="color: #008000;">字符串方式

    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果要更新的文档在获取或者索引阶段已被另一操作更改,则重试更新操作的次数</span>
    request.retryOnConflict(3<span style="color: #000000;">);

    request.version(</span>2);<span style="color: #008000;">//</span><span style="color: #008000;">设置版本</span>
request.fetchSource(true); //启用_source检索,默认为禁用
    </span><span style="color: #008000;">//</span><span style="color: #008000;">为特定字段配置_source_include</span>
    String[] includes = <span style="color: #0000ff;">new</span> String[]{"updated", "r*"<span style="color: #000000;">};
    String[] excludes </span>=<span style="color: #000000;"> Strings.EMPTY_ARRAY;
    request.fetchSource(</span><span style="color: #0000ff;">new</span> FetchSourceContext(<span style="color: #0000ff;">true</span><span style="color: #000000;">, includes, excludes));

    </span><span style="color: #008000;">//</span><span style="color: #008000;">为指定字段配置_source_exclude</span>
    String[] includes1 =<span style="color: #000000;"> Strings.EMPTY_ARRAY;
    String[] excludes1 </span>= <span style="color: #0000ff;">new</span> String[]{"updated"<span style="color: #000000;">};
    request.fetchSource(</span><span style="color: #0000ff;">new</span> FetchSourceContext(<span style="color: #0000ff;">true</span><span style="color: #000000;">, includes1, excludes1));

    request.detectNoop(</span><span style="color: #0000ff;">false</span>);<span style="color: #008000;">//</span><span style="color: #008000;">禁用noop检测

    </span><span style="color: #008000;">//</span><span style="color: #008000;">无论文档是否存在,脚本都必须运行,即如果脚本尚不存在,则脚本负责创建文档。</span>
    request.scriptedUpsert(<span style="color: #0000ff;">true</span><span style="color: #000000;">);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果不存在,则表明部分文档必须用作upsert文档。</span>
    request.docAsUpsert(<span style="color: #0000ff;">true</span><span style="color: #000000;">);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">设置在继续更新操作之前必须激活的分片副本的数量。</span>
    request.waitForActiveShards(2<span style="color: #000000;">);
    </span><span style="color: #008000;">//</span><span style="color: #008000;">使用ActiveShardCount方式,可以是ActiveShardCount.ALL,ActiveShardCount.ONE或ActiveShardCount.DEFAULT(默认值)</span>

request.waitForActiveShards(ActiveShardCount.ALL);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">同步执行</span>
    UpdateResponse updateResponse =<span style="color: #000000;"> client.update(request);


    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步执行
    </span><span style="color: #008000;">//</span><span style="color: #008000;">DeleteResponse  的典型监听器如下所示:
    </span><span style="color: #008000;">//</span><span style="color: #008000;">异步方法不会阻塞并立即返回。</span>
    ActionListener&lt;UpdateResponse &gt; listener = <span style="color: #0000ff;">new</span> ActionListener&lt;UpdateResponse &gt;<span style="color: #000000;">() {
        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onResponse(UpdateResponse  updateResponse) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">执行成功时调用。 Response以参数方式提供</span>

}

        @Override
        </span><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span><span style="color: #000000;"> onFailure(Exception e) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">在失败的情况下调用。 引发的异常以参数方式提供</span>

}
};
//异步执行获取索引请求需要将UpdateRequest 实例和ActionListener实例传递给异步方法:
client.updateAsync(request, listener);

    </span><span style="color: #008000;">//</span><span style="color: #008000;">Update Response
    </span><span style="color: #008000;">//</span><span style="color: #008000;">返回的UpdateResponse允许检索有关执行操作的信息,如下所示:</span>
    String index =<span style="color: #000000;"> updateResponse.getIndex();
    String type </span>=<span style="color: #000000;"> updateResponse.getType();
    String id </span>=<span style="color: #000000;"> updateResponse.getId();
    </span><span style="color: #0000ff;">long</span> version =<span style="color: #000000;"> updateResponse.getVersion();
    </span><span style="color: #0000ff;">if</span> (updateResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.CREATED) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理第一次创建文档的情况(upsert)</span>
    } <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (updateResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.UPDATED) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理文档被更新的情况</span>
    } <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (updateResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.DELETED) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理文档已被删除的情况</span>
    } <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span> (updateResponse.getResult() ==<span style="color: #000000;"> DocWriteResponse.Result.NOOP) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理文档未受更新影响的情况,即文档上未执行任何操作(noop)</span>

}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">当通过fetchSource方法在UpdateRequest中启用源检索时,响应会包含已更新文档:</span>
    GetResult result = updateResponse.getGetResult();<span style="color: #008000;">//</span><span style="color: #008000;">获取已更新的文档</span>
    <span style="color: #0000ff;">if</span><span style="color: #000000;"> (result.isExists()) {
        String sourceAsString </span>= result.sourceAsString();<span style="color: #008000;">//</span><span style="color: #008000;">获取已更新的文档源(String方式)</span>
        Map&lt;String, Object&gt; sourceAsMap = result.sourceAsMap();<span style="color: #008000;">//</span><span style="color: #008000;">获取已更新的文档源(Map方式)</span>
        <span style="color: #0000ff;">byte</span>[] sourceAsBytes = result.source();<span style="color: #008000;">//</span><span style="color: #008000;">获取已更新的文档源(byte[]方式)</span>
    } <span style="color: #0000ff;">else</span><span style="color: #000000;"> {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理不返回文档源的场景(默认就是这种情况)</span>

}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">也可以检查分片失败:</span>
    ReplicationResponse.ShardInfo shardInfo =<span style="color: #000000;"> updateResponse.getShardInfo();
    </span><span style="color: #0000ff;">if</span> (shardInfo.getTotal() !=<span style="color: #000000;"> shardInfo.getSuccessful()) {
        </span><span style="color: #008000;">//</span><span style="color: #008000;">处理成功分片数量少于总分片数量的情况</span>

}
if (shardInfo.getFailed() > 0) {
for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
String reason
= failure.reason();//处理潜在的失败
}
}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">当针对文档不存在时,响应404状态码,将引发ElasticsearchException,需要按如下方式处理:</span>
    UpdateRequest request5 = <span style="color: #0000ff;">new</span> UpdateRequest("posts", "type", "does_not_exist").doc("field", "value"<span style="color: #000000;">);
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        UpdateResponse updateResponse5 </span>=<span style="color: #000000;"> client.update(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (ElasticsearchException e) {
        </span><span style="color: #0000ff;">if</span> (e.status() ==<span style="color: #000000;"> RestStatus.NOT_FOUND) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">处理由于文档不存在抛出的异常</span>

}
}

    </span><span style="color: #008000;">//</span><span style="color: #008000;">如果存在版本冲突,则会抛出ElasticsearchException:</span>
    UpdateRequest request6 = <span style="color: #0000ff;">new</span> UpdateRequest("posts", "doc", "1"<span style="color: #000000;">)
            .doc(</span>"field", "value"<span style="color: #000000;">)
            .version(</span>1<span style="color: #000000;">);
    </span><span style="color: #0000ff;">try</span><span style="color: #000000;"> {
        UpdateResponse updateResponse6 </span>=<span style="color: #000000;"> client.update(request);
    } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;">(ElasticsearchException e) {
        </span><span style="color: #0000ff;">if</span> (e.status() ==<span style="color: #000000;"> RestStatus.CONFLICT) {
            </span><span style="color: #008000;">//</span><span style="color: #008000;">引发的异常表示返回了版本冲突错误</span>

}
}

复制代码

官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.2/java-rest-high.html

原文地址:https://www.cnblogs.com/jpfss/p/10710486.html