RestHighLevelClient操作ES的API


Create Index API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        CreateIndexRequest request = new CreateIndexRequest("twitter_two");//創建索引
        //創建的每個索引都可以有與之關聯的特定設置。
        request.settings(Settings.builder()
                .put("index.number_of_shards", 3)
                .put("index.number_of_replicas", 2)
        );
        //創建索引時創建文檔類型映射
        request.mapping("tweet",//類型定義
                "  {\n" +
                        "    \"tweet\": {\n" +
                        "      \"properties\": {\n" +
                        "        \"message\": {\n" +
                        "          \"type\": \"text\"\n" +
                        "        }\n" +
                        "      }\n" +
                        "    }\n" +
                        "  }",//類型映射,需要的是一個JSON字符串
                XContentType.JSON);
 
        //為索引設置一個別名
        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形式表示。
 
        //同步執行
        CreateIndexResponse createIndexResponse = client.indices().create(request);
        //異步執行
        //異步執行創建索引請求需要將CreateIndexRequest實例和ActionListener實例傳遞給異步方法:
        //CreateIndexResponse的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<CreateIndexResponse> listener = new ActionListener<CreateIndexResponse>() {
            @Override
            public void onResponse(CreateIndexResponse createIndexResponse) {
                //如果執行成功,則調用onResponse方法;
            }
            @Override
            public void onFailure(Exception e) {
                //如果失敗,則調用onFailure方法。
            }
        };
        client.indices().createAsync(request, listener);//要執行的CreateIndexRequest和執行完成時要使用的ActionListener
 
        //返回的CreateIndexResponse允許檢索有關執行的操作的信息,如下所示:
        boolean acknowledged = createIndexResponse.isAcknowledged();//指示是否所有節點都已確認請求
        boolean shardsAcknowledged = createIndexResponse.isShardsAcknowledged();//指示是否在超時之前為索引中的每個分片啟動了必需的分片副本數

Delete Index API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        DeleteIndexRequest request = new DeleteIndexRequest("twitter_two");//指定要刪除的索引名稱
        //可選參數:
        request.timeout(TimeValue.timeValueMinutes(2)); //設置超時,等待所有節點確認索引刪除(使用TimeValue形式)
        // request.timeout("2m"); //設置超時,等待所有節點確認索引刪除(使用字符串形式)
 
        request.masterNodeTimeout(TimeValue.timeValueMinutes(1));連接master節點的超時時間(使用TimeValue方式)
        // request.masterNodeTimeout("1m");//連接master節點的超時時間(使用字符串方式)
 
        //設置IndicesOptions控制如何解決不可用的索引以及如何擴展通配符表達式
        request.indicesOptions(IndicesOptions.lenientExpandOpen());
 
        //同步執行
        DeleteIndexResponse deleteIndexResponse = 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);*/
 
        //Delete Index Response
        //返回的DeleteIndexResponse允許檢索有關執行的操作的信息,如下所示:
        boolean acknowledged = deleteIndexResponse.isAcknowledged();//是否所有節點都已確認請求
 
 
        //如果找不到索引,則會拋出ElasticsearchException:
        try {
            request = new DeleteIndexRequest("does_not_exist");
            client.indices().delete(request);
        } catch (ElasticsearchException exception) {
            if (exception.status() == RestStatus.NOT_FOUND) {
                //如果沒有找到要刪除的索引,要執行某些操作
            }
        }

Open Index API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        OpenIndexRequest request = new OpenIndexRequest("twitter");//打開索引
        //可選參數:
        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.ONE);//在打開索引API返回響應之前等待的活動分片副本的數量,以ActiveShardCount形式表示。
 
        //設置IndicesOptions控制如何解決不可用的索引以及如何擴展通配符表達式
        request.indicesOptions(IndicesOptions.strictExpandOpen());
 
        //同步執行
        OpenIndexResponse openIndexResponse = client.indices().open(request);
 
        /*//異步執行打開索引請求需要將OpenIndexRequest實例和ActionListener實例傳遞給異步方法:
        //OpenIndexResponse的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<OpenIndexResponse> listener = new ActionListener<OpenIndexResponse>() {
            @Override
            public void onResponse(OpenIndexResponse openIndexResponse) {
                //如果執行成功,則調用onResponse方法;
            }
            @Override
            public void onFailure(Exception e) {
                //如果失敗,則調用onFailure方法。
            }
        };
        client.indices().openAsync(request, listener);*/
 
        //Open Index Response
        //返回的OpenIndexResponse允許檢索有關執行的操作的信息,如下所示:
        boolean acknowledged = openIndexResponse.isAcknowledged();//指示是否所有節點都已確認請求
        boolean shardsAcknowledged = openIndexResponse.isShardsAcknowledged();//指示是否在超時之前為索引中的每個分片啟動了必需的分片副本數

Close Index API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
        CloseIndexRequest request = new CloseIndexRequest("index");//關閉索引
 
        //可選參數:
        request.timeout(TimeValue.timeValueMinutes(2)); //設置超時,等待所有節點確認索引已關閉(使用TimeValue形式)
        // request.timeout("2m"); //設置超時,等待所有節點確認索引已關閉(使用字符串形式)
 
        request.masterNodeTimeout(TimeValue.timeValueMinutes(1));連接master節點的超時時間(使用TimeValue方式)
        // request.masterNodeTimeout("1m");//連接master節點的超時時間(使用字符串方式)
 
        //設置IndicesOptions控制如何解決不可用的索引以及如何擴展通配符表達式
        request.indicesOptions(IndicesOptions.lenientExpandOpen());
        //同步執行
        CloseIndexResponse closeIndexResponse = client.indices().close(request);
 
         /*//異步執行打開索引請求需要將CloseIndexRequest實例和ActionListener實例傳遞給異步方法:
        //CloseIndexResponse的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<CloseIndexResponse> listener = new ActionListener<CloseIndexResponse>() {
            @Override
            public void onResponse(CloseIndexResponse closeIndexResponse) {
                 //如果執行成功,則調用onResponse方法;
            }
            @Override
            public void onFailure(Exception e) {
                 //如果失敗,則調用onFailure方法。
            }
        };
        client.indices().closeAsync(request, listener); */
 
        //Close Index Response
        //返回的CloseIndexResponse 允許檢索有關執行的操作的信息,如下所示:
        boolean acknowledged = closeIndexResponse.isAcknowledged(); //指示是否所有節點都已確認請求

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
 
       //==============================提供文檔源========================================
       //方式1:以字符串形式提供
       String jsonString = "{" +
               "\"user\":\"kimchy\"," +
               "\"postDate\":\"2013-01-30\"," +
               "\"message\":\"trying out Elasticsearch\"" +
               "}";
       indexRequest1.source(jsonString, XContentType.JSON);
 
       //方式2:以Map形式提供
       Map<String, Object> jsonMap = new HashMap<>();
       jsonMap.put("user", "kimchy");
       jsonMap.put("postDate", new Date());
       jsonMap.put("message", "trying out Elasticsearch");
       //Map會自動轉換為JSON格式的文檔源
       IndexRequest indexRequest2 = new IndexRequest("posts", "doc", "1")
               .source(jsonMap);
 
       // 方式3:文檔源以XContentBuilder對象的形式提供,Elasticsearch內部會幫我們生成JSON內容
 
       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);
 
       //方式4:以Object key-pairs提供的文檔源,它會被轉換為JSON格式
       IndexRequest indexRequest4 = new IndexRequest("posts", "doc", "1")
        .source("user", "kimchy",
               "postDate", new Date(),
               "message", "trying out Elasticsearch");
 
       //===============================可選參數start====================================
       indexRequest1.routing("routing");//設置路由值
       indexRequest1.parent("parent");//設置parent值
 
       //設置超時:等待主分片變得可用的時間
       indexRequest1.timeout(TimeValue.timeValueSeconds(1));//TimeValue方式
       indexRequest1.timeout("1s");//字符串方式
 
       //刷新策略
       indexRequest1.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);//WriteRequest.RefreshPolicy實例方式
       indexRequest1.setRefreshPolicy("wait_for");//字符串方式
 
       indexRequest1.version(2);//設置版本
 
       indexRequest1.versionType(VersionType.EXTERNAL);//設置版本類型
 
       //操作類型
       indexRequest1.opType(DocWriteRequest.OpType.CREATE);//DocWriteRequest.OpType方式
       indexRequest1.opType("create");//字符串方式, 可以是 create 或 update (默認)
 
       //The name of the ingest pipeline to be executed before indexing the document
       indexRequest1.setPipeline("pipeline");
       
       //===============================執行====================================
       //同步執行
       IndexResponse indexResponse = client.index(indexRequest1);
 
       //異步執行
       //IndexResponse 的典型監聽器如下所示:
       //異步方法不會阻塞並立即返回。
       ActionListener<IndexResponse> listener = new ActionListener<IndexResponse>() {
           @Override
           public void onResponse(IndexResponse indexResponse) {
                //執行成功時調用。 Response以參數方式提供
           }
 
           @Override
           public void onFailure(Exception e) {
               //在失敗的情況下調用。 引發的異常以參數方式提供
           }
       };
       //異步執行索引請求需要將IndexRequest實例和ActionListener實例傳遞給異步方法:
       client.indexAsync(indexRequest2, listener);
 
       //Index Response
       //返回的IndexResponse允許檢索有關執行操作的信息,如下所示:
       String index = indexResponse.getIndex();
       String type = indexResponse.getType();
       String id = indexResponse.getId();
       long version = indexResponse.getVersion();
       if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
            //處理(如果需要)第一次創建文檔的情況
       } else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
            //處理(如果需要)文檔被重寫的情況
       }
       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();//處理潛在的失敗
           }
       }
 
       //如果存在版本沖突,則會拋出ElasticsearchException:
       IndexRequest request = new IndexRequest("posts", "doc", "1")
               .source("field", "value")
               .version(1);
       try {
           IndexResponse response = client.index(request);
       } catch(ElasticsearchException e) {
           if (e.status() == RestStatus.CONFLICT) {
                //引發的異常表示返回了版本沖突錯誤
           }
       }
 
       //如果opType設置為創建但是具有相同索引,類型和ID的文檔已存在,則也會發生同樣的情況:
       request = new IndexRequest("posts", "doc", "1")
               .source("field", "value")
               .opType(DocWriteRequest.OpType.CREATE);
       try {
           IndexResponse response = client.index(request);
       } catch(ElasticsearchException e) {
           if (e.status() == RestStatus.CONFLICT) {
                //引發的異常表示返回了版本沖突錯誤
           }
       }

Get API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        GetRequest getRequest = new GetRequest(
                "posts",//索引
                "doc",//類型
                "1");//文檔ID
 
        //===============================可選參數start====================================
        //禁用_source檢索,默認為啟用
        getRequest.fetchSourceContext(new FetchSourceContext(false));
 
 
        //為特定字段配置_source_include
        String[] includes = new String[]{"message", "*Date"};
        String[] excludes = Strings.EMPTY_ARRAY;
        FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
        getRequest.fetchSourceContext(fetchSourceContext);
 
        //為指定字段配置_source_exclude
        String[] includes1 = Strings.EMPTY_ARRAY;
        String[] excludes1 = new String[]{"message"};
        FetchSourceContext fetchSourceContext1 = new FetchSourceContext(true, includes, excludes);
        getRequest.fetchSourceContext(fetchSourceContext);
 
        //配置指定stored_fields的檢索(要求字段在映射中單獨存儲)
        getRequest.storedFields("message");
        GetResponse getResponse = client.get(getRequest);
        //檢索message 存儲字段(要求將字段分開存儲在映射中)
        String message = getResponse.getField("message").getValue();
 
        getRequest.routing("routing");//設置routing值
        getRequest.parent("parent");//設置parent值
        getRequest.preference("preference");//設置preference值
        getRequest.realtime(false);//設置realtime為false,默認是true
        getRequest.refresh(true);//在檢索文檔之前執行刷新(默認為false)
        getRequest.version(2);//設置版本
        getRequest.versionType(VersionType.EXTERNAL);//設置版本類型
        //===============================可選參數end====================================
 
        //同步執行
        GetResponse getResponse1 = client.get(getRequest);
 
 
        //異步執行
        //GetResponse 的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<GetResponse> listener = new ActionListener<GetResponse>() {
            @Override
            public void onResponse(GetResponse getResponse) {
                //執行成功時調用。 Response以參數方式提供
            }
 
            @Override
            public void onFailure(Exception e) {
                //在失敗的情況下調用。 引發的異常以參數方式提供
            }
        };
        //異步執行獲取索引請求需要將GetRequest 實例和ActionListener實例傳遞給異步方法:
        client.getAsync(getRequest, listener);
 
 
        //Get Response
        //返回的GetResponse允許檢索請求的文檔及其元數據和最終存儲的字段。
        String index = getResponse.getIndex();
        String type = getResponse.getType();
        String id = getResponse.getId();
        if (getResponse.isExists()) {
            long version = getResponse.getVersion();
            String sourceAsString = getResponse.getSourceAsString();//檢索文檔(String形式)
            Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();//檢索文檔(Map<String, Object>形式)
            byte[] sourceAsBytes = getResponse.getSourceAsBytes();//檢索文檔(byte[]形式)
        } else {
           /* 處理找不到文檔的情況。 請注意,盡管返回404狀態碼,
            但返回的是有效的GetResponse,而不是拋出的異常。
            此類Response不包含任何源文檔,並且其isExists方法返回false。*/
        }
 
 
        //當針對不存在的索引執行獲取請求時,響應404狀態碼,將引發ElasticsearchException,需要按如下方式處理:
        GetRequest request = new GetRequest("does_not_exist", "doc", "1");
        try {
            GetResponse getResponse2 = client.get(request);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                //處理因為索引不存在而拋出的異常情況
            }
        }
 
        //如果請求了特定的文檔版本,並且現有文檔具有不同的版本號,則會引發版本沖突:
        try {
            GetRequest request1 = new GetRequest("posts", "doc", "1").version(2);
            GetResponse getResponse3 = client.get(request);
        } catch (ElasticsearchException exception) {
            if (exception.status() == RestStatus.CONFLICT) {
                //引發的異常表示返回了版本沖突錯誤
            }
        }

Delete API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        DeleteRequest request = new DeleteRequest (
                "posts",//索引
                "doc",//類型
                "1");//文檔ID
 
        //===============================可選參數====================================
        request.routing("routing");//設置routing值
        request.parent("parent");//設置parent值
 
        //設置超時:等待主分片變得可用的時間
        request.timeout(TimeValue.timeValueMinutes(2));//TimeValue方式
        request.timeout("1s");//字符串方式
 
        //刷新策略
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);//WriteRequest.RefreshPolicy實例方式
        request.setRefreshPolicy("wait_for");//字符串方式
 
        request.version(2);//設置版本
        request.versionType(VersionType.EXTERNAL);//設置版本類型
 
        //同步執行
        DeleteResponse deleteResponse = client.delete(request);
 
 
        //異步執行
        //DeleteResponse  的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<DeleteResponse > listener = new ActionListener<DeleteResponse >() {
            @Override
            public void onResponse(DeleteResponse  getResponse) {
                //執行成功時調用。 Response以參數方式提供
            }
 
            @Override
            public void onFailure(Exception e) {
                //在失敗的情況下調用。 引發的異常以參數方式提供
            }
        };
        //異步執行獲取索引請求需要將DeleteRequest  實例和ActionListener實例傳遞給異步方法:
        client.deleteAsync(request, listener);
 
        //Delete Response
        //返回的DeleteResponse允許檢索有關執行操作的信息,如下所示:
        String index = deleteResponse.getIndex();
        String type = deleteResponse.getType();
        String id = deleteResponse.getId();
        long version = deleteResponse.getVersion();
        ReplicationResponse.ShardInfo shardInfo = deleteResponse.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
            //處理成功分片數量少於總分片數量的情況
        }
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                String reason = failure.reason();//處理潛在的失敗
            }
        }
 
        //還可以檢查文檔是否被找到:
        DeleteRequest request1 = new DeleteRequest("posts", "doc", "does_not_exist");
        DeleteResponse deleteResponse1 = client.delete(request);
        if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
           //如果找不到要刪除的文檔,執行某些操作
        }
 
        //如果存在版本沖突,則會拋出ElasticsearchException:
        try {
            DeleteRequest request2 = new DeleteRequest("posts", "doc", "1").version(2);
            DeleteResponse deleteResponse2 = client.delete(request);
        } catch (ElasticsearchException exception) {
            if (exception.status() == RestStatus.CONFLICT) {
                //引發的異常表示返回了版本沖突錯誤
            }
        }

Update API

RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9201, "http")));
 
        UpdateRequest request = new UpdateRequest  (
                "test",//索引
                "_doc",//類型
                "1");//文檔ID
 
        //更新API允許通過使用腳本或傳遞部分文檔來更新現有文檔。
 
        //使用腳本
        //方式1:該腳本可以作為內聯腳本提供:
        Map<String, Object> parameters = singletonMap("count", 4);//腳本參數
        //使用painless語言和上面的參數創建一個內聯腳本
        Script inline = new Script(ScriptType.INLINE, "painless", "ctx._source.field += params.count", parameters);
        request.script(inline);
 
        //方式2:引用名稱為increment-field的腳本,改腳本定義的位置還沒搞清楚。
        Script stored =
                new Script(ScriptType.STORED, null, "increment-field", parameters);
        request.script(stored);
 
        //只更新部分
        //更新部分文檔時,更新的部分文檔將與現有文檔合並。
 
        //方式1:使用字符串形式
        UpdateRequest request1 = new UpdateRequest("posts", "doc", "1");
        String jsonString = "{" +
                "\"updated\":\"2017-01-01\"," +
                "\"reason\":\"daily update\"" +
                "}";
        request1.doc(jsonString, XContentType.JSON);
 
        //方式2:使用Map形式,會被自動轉為json格式
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("updated", new Date());
        jsonMap.put("reason", "daily update");
        UpdateRequest request2 = new UpdateRequest("posts", "doc", "1")
                .doc(jsonMap);
 
 
        //方式3:使用XContentBuilder形式
        XContentBuilder builder = XContentFactory.jsonBuilder();
        builder.startObject();
        {
            builder.field("updated", new Date());
            builder.field("reason", "daily update");
        }
        builder.endObject();
        UpdateRequest request3 = new UpdateRequest("posts", "doc", "1")
                .doc(builder);
 
 
        //方式4:使用Object key-pairs形式
        UpdateRequest request4 = new UpdateRequest("posts", "doc", "1")
                .doc("updated", new Date(),
                        "reason", "daily update");
 
 
        //如果文檔尚不存在,則可以使用upsert方法定義一些將作為新文檔插入的內容:
        //與部分文檔更新類似,可以使用接受String,Map,XContentBuilder或Object key-pairs的方式來定義upsert文檔的內容。
        String jsonString1 = "{\"created\":\"2017-01-01\"}";
        request.upsert(jsonString1, XContentType.JSON);
 
        //=========================可選參數===========================
        request.routing("routing");//設置routing值
        request.parent("parent");//設置parent值
 
        //設置超時:等待主分片變得可用的時間
        request.timeout(TimeValue.timeValueSeconds(1));//TimeValue方式
        request.timeout("1s");//字符串方式
 
        //刷新策略
        request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);//WriteRequest.RefreshPolicy實例方式
        request.setRefreshPolicy("wait_for");//字符串方式
 
        //如果要更新的文檔在獲取或者索引階段已被另一操作更改,則重試更新操作的次數
        request.retryOnConflict(3);
 
        request.version(2);//設置版本
 
        request.fetchSource(true); //啟用_source檢索,默認為禁用
 
        //為特定字段配置_source_include
        String[] includes = new String[]{"updated", "r*"};
        String[] excludes = Strings.EMPTY_ARRAY;
        request.fetchSource(new FetchSourceContext(true, includes, excludes));
 
        //為指定字段配置_source_exclude
        String[] includes1 = Strings.EMPTY_ARRAY;
        String[] excludes1 = new String[]{"updated"};
        request.fetchSource(new FetchSourceContext(true, includes1, excludes1));
 
        request.detectNoop(false);//禁用noop檢測
 
        //無論文檔是否存在,腳本都必須運行,即如果腳本尚不存在,則腳本負責創建文檔。
        request.scriptedUpsert(true);
 
        //如果不存在,則表明部分文檔必須用作upsert文檔。
        request.docAsUpsert(true);
 
        //設置在繼續更新操作之前必須激活的分片副本的數量。
        request.waitForActiveShards(2);
        //使用ActiveShardCount方式,可以是ActiveShardCount.ALL,ActiveShardCount.ONE或ActiveShardCount.DEFAULT(默認值)
        request.waitForActiveShards(ActiveShardCount.ALL);
 
        //同步執行
        UpdateResponse updateResponse = client.update(request);
 
 
        //異步執行
        //DeleteResponse  的典型監聽器如下所示:
        //異步方法不會阻塞並立即返回。
        ActionListener<UpdateResponse > listener = new ActionListener<UpdateResponse >() {
            @Override
            public void onResponse(UpdateResponse  updateResponse) {
                //執行成功時調用。 Response以參數方式提供
            }
 
            @Override
            public void onFailure(Exception e) {
                //在失敗的情況下調用。 引發的異常以參數方式提供
            }
        };
        //異步執行獲取索引請求需要將UpdateRequest  實例和ActionListener實例傳遞給異步方法:
        client.updateAsync(request, listener);
 
        //Update Response
        //返回的UpdateResponse允許檢索有關執行操作的信息,如下所示:
        String index = updateResponse.getIndex();
        String type = updateResponse.getType();
        String id = updateResponse.getId();
        long version = updateResponse.getVersion();
        if (updateResponse.getResult() == DocWriteResponse.Result.CREATED) {
            //處理第一次創建文檔的情況(upsert)
        } else if (updateResponse.getResult() == DocWriteResponse.Result.UPDATED) {
            //處理文檔被更新的情況
        } else if (updateResponse.getResult() == DocWriteResponse.Result.DELETED) {
            //處理文檔已被刪除的情況
        } else if (updateResponse.getResult() == DocWriteResponse.Result.NOOP) {
            //處理文檔未受更新影響的情況,即文檔上未執行任何操作(noop)
        }
 
        //當通過fetchSource方法在UpdateRequest中啟用源檢索時,響應會包含已更新文檔:
        GetResult result = updateResponse.getGetResult();//獲取已更新的文檔
        if (result.isExists()) {
            String sourceAsString = result.sourceAsString();//獲取已更新的文檔源(String方式)
            Map<String, Object> sourceAsMap = result.sourceAsMap();//獲取已更新的文檔源(Map方式)
            byte[] sourceAsBytes = result.source();//獲取已更新的文檔源(byte[]方式)
        } else {
            //處理不返回文檔源的場景(默認就是這種情況)
        }
 
 
        //也可以檢查分片失敗:
        ReplicationResponse.ShardInfo shardInfo = updateResponse.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
            //處理成功分片數量少於總分片數量的情況
        }
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                String reason = failure.reason();//處理潛在的失敗
            }
        }
 
        //當針對文檔不存在時,響應404狀態碼,將引發ElasticsearchException,需要按如下方式處理:
        UpdateRequest request5 = new UpdateRequest("posts", "type", "does_not_exist").doc("field", "value");
        try {
            UpdateResponse updateResponse5 = client.update(request);
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                //處理由於文檔不存在拋出的異常
            }
        }
 
        //如果存在版本沖突,則會拋出ElasticsearchException:
        UpdateRequest request6 = new UpdateRequest("posts", "doc", "1")
                .doc("field", "value")
                .version(1);
        try {
            UpdateResponse updateResponse6 = client.update(request);
        } catch(ElasticsearchException e) {
            if (e.status() == RestStatus.CONFLICT) {
                //引發的異常表示返回了版本沖突錯誤
            }
        }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM