国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Elasticsearch Java REST Client 批量操作(Bulk API)

這篇具有很好參考價(jià)值的文章主要介紹了Elasticsearch Java REST Client 批量操作(Bulk API)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

上一篇:Elasticsearch Java REST Client Term Vectors API
下一篇:Elasticsearch Java REST Client Search APIs 查詢文章來源地址http://www.zghlxwxcb.cn/news/detail-515835.html

BulkRequest

BulkRequest可用于使用單個(gè)請(qǐng)求執(zhí)行多個(gè)索引、更新和/或刪除操作。
它需要至少一個(gè)操作添加到 Bulk 請(qǐng)求中:

# 方式一:
@GetMapping("test")
public String test() throws IOException {
    BulkRequest request = new BulkRequest();
    request.add(new IndexRequest("edu-app-user", "doc", "1")
            .source(XContentType.JSON, "name", "foo"));
    request.add(new IndexRequest("edu-app-user", "doc", "2")
            .source(XContentType.JSON, "name", "elastic"));
    request.add(new IndexRequest("edu-app-user", "doc", "3")
            .source(XContentType.JSON, "name", "wdz"));

    BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
    return response(bulk);
}
# 混合操作
@GetMapping("test1")
public String test1() throws IOException {
     BulkRequest request = new BulkRequest();
     request.add(new DeleteRequest("edu-app-user", "doc", "3"));
     request.add(new UpdateRequest("edu-app-user", "doc", "2")
             .doc(XContentType.JSON, "name", "update"));
     request.add(new IndexRequest("edu-app-user", "doc", "4")
             .source(XContentType.JSON, "name", "baz"));
     BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
     return response(bulk);
 }
private String response(BulkResponse bulk){
    String str = "";
    for (BulkItemResponse responses : bulk) {
        System.out.println(responses.toString());
        DocWriteResponse response = responses.getResponse();
        switch (responses.getOpType()) {
            case CREATE:
                System.out.println("創(chuàng)建數(shù)據(jù)-----------------");
                break;
            case INDEX:
                IndexResponse indexResponse = (IndexResponse) response;
                System.out.println("操作索引數(shù)據(jù)-----------------"+indexResponse.toString());
                str = indexResponse.toString();
                break;
            case DELETE:
                DeleteResponse deleteResponse = (DeleteResponse) response;
                System.out.println("操作刪除數(shù)據(jù)-----------------"+deleteResponse.toString());
                str = deleteResponse.toString();
                break;
            case UPDATE:
                UpdateResponse updateResponse = (UpdateResponse) response;
                System.out.println("操作更新數(shù)據(jù)-----------------"+updateResponse.toString());
                str = updateResponse.toString();
                break ;
        }
    }
    return str;
}
# 異步處理
@GetMapping("test3")
public void test3() throws IOException {
    BulkRequest request = new BulkRequest();
    request.add(new DeleteRequest("edu-app-user", "doc", "3"));
    request.add(new UpdateRequest("edu-app-user", "doc", "100")
            .doc(XContentType.JSON, "name", "update"));
    request.add(new IndexRequest("edu-app-user", "doc", "1")
            .source(XContentType.JSON, "name", "baz"));
    restHighLevelClient.bulkAsync(request, RequestOptions.DEFAULT,new BulkListen());
}
# 監(jiān)聽
package com.wdz.es.config.es;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;

public class BulkListen implements ActionListener<BulkResponse> {
    @Override
    public void onResponse(BulkResponse bulkItemResponses) {
        String response = response(bulkItemResponses);
        System.out.println("異步成功: "+response);
    }

    @Override
    public void onFailure(Exception e) {
        System.out.println("異步處理失敗:"+e.getMessage());
    }

    public static String response(BulkResponse bulk) {
        String str = "";
        for (BulkItemResponse responses : bulk) {
            System.out.println(responses.toString());
            DocWriteResponse response = responses.getResponse();

            switch (responses.getOpType()) {
                case CREATE:
                    System.out.println("創(chuàng)建數(shù)據(jù)-----------------");
                    break;
                case INDEX:
                    IndexResponse indexResponse = (IndexResponse) response;
                    System.out.println("操作索引數(shù)據(jù)-----------------" + indexResponse.toString());
                    str = indexResponse.toString();
                    break;
                case DELETE:
                    DeleteResponse deleteResponse = (DeleteResponse) response;
                    System.out.println("操作刪除數(shù)據(jù)-----------------" + deleteResponse.toString());
                    str = deleteResponse.toString();
                    break;
                case UPDATE:
                    UpdateResponse updateResponse = (UpdateResponse) response;
                    System.out.println("操作更新數(shù)據(jù)-----------------" + updateResponse.toString());
                    str = updateResponse.toString();
                    break;
            }
            // 獲取失敗的處理
            BulkItemResponse.Failure failure = responses.getFailure();
            System.out.println(failure.toString());
        }
        return str;
    }
}

# 結(jié)果
org.elasticsearch.action.bulk.BulkItemResponse@6ca820cd
操作刪除數(shù)據(jù)-----------------DeleteResponse[index=edu-app-user,type=doc,id=3,version=4,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
org.elasticsearch.action.bulk.BulkItemResponse@25ae673
操作更新數(shù)據(jù)-----------------UpdateResponse[index=edu-app-user,type=doc,id=2,version=4,seqNo=5,primaryTerm=1,result=updated,shards=ShardInfo{total=2, successful=1, failures=[]}]
org.elasticsearch.action.bulk.BulkItemResponse@5e6d6373
操作索引數(shù)據(jù)-----------------IndexResponse[index=edu-app-user,type=doc,id=4,version=1,result=created,seqNo=6,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]

可選操作

# 設(shè)置超時(shí)時(shí)間(兩種方式)
request.timeout(TimeValue.timeValueMinutes(2)); 
request.timeout("2m"); 
# 設(shè)置在繼續(xù)執(zhí)行索引/更新/刪除操作之前必須處于活動(dòng)狀態(tài)的分片副本數(shù)。
request.waitForActiveShards(2); 
# 提供的分片副本數(shù)ActiveShardCount: 可以是 ActiveShardCount.ALL,ActiveShardCount.ONE或 ActiveShardCount.DEFAULT(默認(rèn))
request.waitForActiveShards(ActiveShardCount.ALL); 	

批處理 BulkProcessor

@GetMapping("test2")
public void test2() throws IOException {
   BulkProcessor.Listener listener = new BulkProcessor.Listener() {
       @Override
       public void beforeBulk(long executionId, BulkRequest request) {
           System.out.println(executionId+"批處理之前request:"+JSONObject.toJSONString(request));
       }
       @Override
       public void afterBulk(long executionId, BulkRequest request,
                             BulkResponse response) {
           System.out.println(executionId+"批處理之后request:"+JSONObject.toJSONString(request));
           System.out.println(executionId+"批處理之后response:"+JSONObject.toJSONString(response));
       }
       @Override
       public void afterBulk(long executionId, BulkRequest request,
                             Throwable failure) {
           System.out.println(executionId+"批處理異常request:"+JSONObject.toJSONString(request));
           System.out.println(executionId+"批處理異常failure:"+failure.getMessage());
       }
   };

   BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer =
           (request, bulkListener) ->
                   restHighLevelClient.bulkAsync(request, RequestOptions.DEFAULT, bulkListener);
   BulkProcessor bulkProcessor =
            BulkProcessor.builder(bulkConsumer, listener).build();
   bulkProcessor.add(new IndexRequest("edu-app-user","doc","1002").source(XContentType.JSON,"name","BulkProcessor"));
   bulkProcessor.add(new DeleteRequest("edu-app-user","doc","2"));
   bulkProcessor.add(new UpdateRequest("edu-app-user","doc","28").doc(XContentType.JSON,"name","更新測(cè)試"));
   // 這兩種方法都在關(guān)閉處理器之前刷新添加到處理器的請(qǐng)求,并且還禁止向其添加任何新請(qǐng)求
   // 直到所有請(qǐng)求都已處理或指定的等待時(shí)間過去
   try {
       bulkProcessor.awaitClose(30L, TimeUnit.SECONDS);
   } catch (InterruptedException e) {
       e.printStackTrace();
   }
   // 該close()方法可用于立即關(guān)閉BulkProcessor
   bulkProcessor.close();
   System.out.println(JSONObject.toJSONString(bulkConsumer));
   System.out.println(JSONObject.toJSONString(add));
   System.out.println(JSONObject.toJSONString(bulkProcessor));
}
# 異常結(jié)果
1批處理之前request:{"description":"requests[1], indices[bulk-test]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
1批處理異常request:{"description":"requests[1], indices[bulk-test]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
1批處理異常failure:Validation Failed: 1: source is missing;2: content type is missing;
{}
{}
{}
# 成功結(jié)果
1批處理之前request:{"description":"requests[1], indices[edu-app-user]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
{}
{}
{}
1批處理之后request:{"description":"requests[1], indices[edu-app-user]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
1批處理之后response:{"fragment":false,"ingestTook":{"days":0,"daysFrac":-1.1574074074074074E-8,"hours":0,"hoursFrac":-2.7777777777777776E-7,"micros":-1000,"microsFrac":-1000.0,"millis":-1,"millisFrac":-1.0,"minutes":0,"minutesFrac":-1.6666666666666667E-5,"nanos":-1000000,"seconds":0,"secondsFrac":-0.001,"stringRep":"-1"},"ingestTookInMillis":-1,"items":[{"failed":false,"fragment":false,"id":"100","index":"edu-app-user","itemId":0,"opType":"INDEX","response":{"fragment":false,"id":"100","index":"edu-app-user","primaryTerm":1,"result":"CREATED","seqNo":1,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"edu-app-user","uUID":"_na_"},"indexName":"edu-app-user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"doc","version":1},"type":"doc","version":1}],"took":{"days":0,"daysFrac":1.0300925925925926E-6,"hours":0,"hoursFrac":2.4722222222222223E-5,"micros":89000,"microsFrac":89000.0,"millis":89,"millisFrac":89.0,"minutes":0,"minutesFrac":0.0014833333333333332,"nanos":89000000,"seconds":0,"secondsFrac":0.089,"stringRep":"89ms"}}

# 混合批處理結(jié)果
1批處理之前request:{"description":"requests[3], indices[edu-app-user]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
{}
{}
{}
1批處理之后request:{"description":"requests[3], indices[edu-app-user]","parentTask":{"id":-1,"nodeId":"","set":false},"refreshPolicy":"NONE","shouldStoreResult":false}
1批處理之后response:{"fragment":false,"ingestTook":{"days":0,"daysFrac":-1.1574074074074074E-8,"hours":0,"hoursFrac":-2.7777777777777776E-7,"micros":-1000,"microsFrac":-1000.0,"millis":-1,"millisFrac":-1.0,"minutes":0,"minutesFrac":-1.6666666666666667E-5,"nanos":-1000000,"seconds":0,"secondsFrac":-0.001,"stringRep":"-1"},"ingestTookInMillis":-1,"items":[{"failed":false,"fragment":false,"id":"1002","index":"edu-app-user","itemId":0,"opType":"INDEX","response":{"fragment":false,"id":"1002","index":"edu-app-user","primaryTerm":1,"result":"CREATED","seqNo":16,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"edu-app-user","uUID":"_na_"},"indexName":"edu-app-user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"doc","version":1},"type":"doc","version":1},{"failed":false,"fragment":false,"id":"2","index":"edu-app-user","itemId":1,"opType":"DELETE","response":{"fragment":false,"id":"2","index":"edu-app-user","primaryTerm":1,"result":"DELETED","seqNo":7,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"edu-app-user","uUID":"_na_"},"indexName":"edu-app-user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"doc","version":5},"type":"doc","version":5},{"failed":false,"fragment":false,"id":"28","index":"edu-app-user","itemId":2,"opType":"UPDATE","response":{"fragment":false,"id":"28","index":"edu-app-user","primaryTerm":1,"result":"UPDATED","seqNo":17,"shardId":{"fragment":true,"id":-1,"index":{"fragment":false,"name":"edu-app-user","uUID":"_na_"},"indexName":"edu-app-user"},"shardInfo":{"failed":0,"failures":[],"fragment":false,"successful":1,"total":2},"type":"doc","version":8},"type":"doc","version":8}],"took":{"days":0,"daysFrac":1.0069444444444445E-6,"hours":0,"hoursFrac":2.4166666666666667E-5,"micros":87000,"microsFrac":87000.0,"millis":87,"millisFrac":87.0,"minutes":0,"minutesFrac":0.00145,"nanos":87000000,"seconds":0,"secondsFrac":0.087,"stringRep":"87ms"}}

multi Get API 多獲取

multiGetAPI 在單個(gè) http 請(qǐng)求中并行執(zhí)行多個(gè)請(qǐng)求get 。
MultiGetRequest,添加 `MultiGetRequest.Item 來配置要獲取的內(nèi)容:

@GetMapping("get")
public MultiGetResponse get(){
     MultiGetRequest request = new MultiGetRequest();
     MultiGetRequest.Item item = new MultiGetRequest.Item(index, type, "28");
     MultiGetRequest.Item item1 = new MultiGetRequest.Item(index, type, "1");
     MultiGetRequest.Item item2 = new MultiGetRequest.Item(index, type, "3");
     request.add(item);
     request.add(item1);
     request.add(item2);
     MultiGetResponse mget = null;
     try {
         mget = restHighLevelClient.mget(request, RequestOptions.DEFAULT);
     } catch (IOException e) {
         e.printStackTrace();
     }
     return mget;
 }

可選參數(shù):

# 禁用抓取_source
new MultiGetRequest.Item("index", "type", "example_id").fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE)

# 過濾數(shù)據(jù)
String[] includes = new String[] {"name", "age"};
String[] excludes = Strings.EMPTY_ARRAY;
FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);
request.add(item.fetchSourceContext(fetchSourceContext));
    

多獲取異步處理方式與其他異步一致更新泛型即可

上一篇:Elasticsearch Java REST Client Term Vectors API
下一篇:Elasticsearch Java REST Client Search APIs 查詢

到了這里,關(guān)于Elasticsearch Java REST Client 批量操作(Bulk API)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • elasticsearch bulk 批量操作

    elasticsearch bulk 批量操作

    bulk 請(qǐng)求體如下: { action: { metadata }}n { request body }n { action: { metadata }}n { request body }n 測(cè)試索引示例 PUT batch_test { “mappings”: { “properties”: { “id”:{ “type”: “keyword” }, “name”:{ “type”: “text” }, “age”:{ “type”: “integer” } } } } 測(cè)試原始數(shù)據(jù) PUT /_bulk {“index”:{“_i

    2024年02月07日
    瀏覽(25)
  • ElasticSearch中批量操作(批量查詢_mget、批量插入刪除_bulk)

    ElasticSearch中批量操作(批量查詢_mget、批量插入刪除_bulk)

    有時(shí)候可以通過批量操作來減少網(wǎng)絡(luò)請(qǐng)求。如:批量查詢、批量插入數(shù)據(jù)。 當(dāng)某一條數(shù)據(jù)不存在,不影響整體響應(yīng),需要通過found的值進(jìn)行判斷是否查詢到數(shù)據(jù)。? ????????在Elasticsearch中,支持批量的插入、修改、刪除操作,都是通過_bulk的api完成的。 請(qǐng)求格式如下:(

    2024年02月12日
    瀏覽(32)
  • Elasticsearch學(xué)習(xí)--索引的批量操作mget、bulk

    Elasticsearch學(xué)習(xí)--索引的批量操作mget、bulk

    1. 基本用法 查詢id是1、2的數(shù)據(jù) 2. 提取index ?3. ids的用法 4.?指定source create:不存在則創(chuàng)建,存在則報(bào)錯(cuò) delete:刪除文檔 update:全量替換或部分更新 index:索引(動(dòng)詞) 1. 自動(dòng)生成id ? 2. 刪除操作是懶刪除 并沒有真正的刪除,只是標(biāo)記為刪除? 3. index(可以是創(chuàng)建,也可以

    2024年02月10日
    瀏覽(25)
  • 初識(shí)ElasticSearch(5) -批量操作之bulk | 條件查詢 | 其它查詢

    初識(shí)ElasticSearch(5) -批量操作之bulk | 條件查詢 | 其它查詢

    本系列筆記結(jié)合HTTP請(qǐng)求(使用postman調(diào)用,源文件見GitHub)和ElasticsearchRestTemplate進(jìn)行調(diào)用學(xué)習(xí) ElasticsearchRestTemplate封裝了RestHighLevelClient,有些場(chǎng)景還得用RestHighLevelClient來操作 版本說明:使用的SpringBoot-2.3.5,對(duì)應(yīng)的ElasticSearch-7.6.2;所以還是可以用RestHighLevelClient ElasticSearch-7

    2023年04月08日
    瀏覽(22)
  • 最新版ES8的client API操作 Elasticsearch Java API client 8.0

    最新版ES8的client API操作 Elasticsearch Java API client 8.0

    作者:ChenZhen 本人不常看網(wǎng)站消息,有問題通過下面的方式聯(lián)系: 郵箱:1583296383@qq.com vx: ChenZhen_7 我的個(gè)人博客地址:https://www.chenzhen.space/?? 版權(quán):本文為博主的原創(chuàng)文章,本文版權(quán)歸作者所有,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。?? 如果對(duì)你有幫助,請(qǐng)給一個(gè)小小的s

    2024年02月04日
    瀏覽(29)
  • Java API批量操作Elasticsearch

    Java API批量操作Elasticsearch

    @Test public void batchAddIndex() throws IOException { BulkRequestBuilder bulkRequest = client .prepareBulk(); bulkRequest.add( client .prepareIndex( “batch_test1” , “batch” , “1” ) .setSource( jsonBuilder () .startObject() .field( “user” , “l(fā)zq” ) .field( “postDate” , new Date()) .field( “message” , “trying out Elasticsearch”

    2024年04月09日
    瀏覽(26)
  • Elasticsearch rest-high-level-client 基本操作

    Elasticsearch rest-high-level-client 基本操作

    本篇主要講解一下 rest-high-level-client 去操作 Elasticsearch , 雖然這個(gè)客戶端在后續(xù)版本中會(huì)慢慢淘汰,但是目前大部分公司中使用Elasticsearch 版本都是6.x 所以這個(gè)客戶端還是有一定的了解 前置準(zhǔn)備 準(zhǔn)備一個(gè)SpringBoot環(huán)境 2.2.11 版本 準(zhǔn)備一個(gè)Elasticsearch 環(huán)境 我這里是8.x版本 引入依賴

    2024年01月22日
    瀏覽(25)
  • 【Elasticsearch學(xué)習(xí)筆記五】es常用的JAVA API、es整合SpringBoot項(xiàng)目中使用、利用JAVA代碼操作es、RestHighLevelClient客戶端對(duì)象

    目錄 一、Maven項(xiàng)目集成Easticsearch 1)客戶端對(duì)象 2)索引操作 3)文檔操作 4)高級(jí)查詢 二、springboot項(xiàng)目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)數(shù)據(jù)實(shí)體類 4)配置類 5)Dao數(shù)據(jù)訪問對(duì)象 6)索引操作 7)文檔操作 8)文檔搜索 三、springboot項(xiàng)目集成bboss操作elasticsearch

    2023年04月09日
    瀏覽(37)
  • SpringBoot整合ElasticSearch之Java High Level REST Client

    SpringBoot整合ElasticSearch之Java High Level REST Client

    1 搭建SpringBoot工程 2 引入ElasticSearch相關(guān)坐標(biāo)。 3 編寫核心配置類 編寫核心配置文件: 這里可以不寫在配置,可以直接寫在代碼中,只是一般都是寫在配置文件中 編寫核心配置類 4 測(cè)試客戶端對(duì)象 記得把maven的單元測(cè)試關(guān)了 注意:使用@Autowired注入RestHighLevelClient 如果報(bào)紅線

    2024年02月05日
    瀏覽(48)
  • (Rest風(fēng)格API)Elasticsearch索引操作、映射配置、數(shù)據(jù)操作、查詢操作

    (Rest風(fēng)格API)Elasticsearch索引操作、映射配置、數(shù)據(jù)操作、查詢操作

    1.請(qǐng)求方式:put 2.請(qǐng)求路徑:索引庫名 3.請(qǐng)求參數(shù):json格式 number_of_shards 是指索引要做多少個(gè)分片,只能在創(chuàng)建索引時(shí)指定,后期無法修改。 number_of_replicas 是指每個(gè)分片有多少個(gè)副本,后期可以動(dòng)態(tài)修改 什么是分片? ES中所存數(shù)據(jù)的文件塊,也是數(shù)據(jù)的最小單元塊。假如有

    2024年04月26日
    瀏覽(21)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包