Home > Software engineering >  How can I create CRUD Operations request in Elasticsearch version 8 using JAVA APIs?
How can I create CRUD Operations request in Elasticsearch version 8 using JAVA APIs?

Time:04-27

We wanted to create IndexRequest, DeleteRequest, UpdateRequest and BulkRequest in Elasticsearch version 8 using JAVA APIs. But I don't see any java documentation in elasticsearch v8 official website. Previously in elasticsearch version 7, we used below code in order to perform operations.

IndexRequest indexRequest = Requests.indexRequest(index).id(key).source(source);


BulkRequest bulkRequest = Requests.bulkRequest();
bulkRequest.add(indexRequest);

Also following Elasticsearch Java API Client [8.1] , but no luck.

Problem arises when we try to do Requests.indexRequest(), this Request class is not available in version 8.

So, Is it possible to create similar request in ES version 8 also?

CodePudding user response:

You can use the refer the following code which I used to bulk index.

String PRODUCT_INDEX="product"
final BulkResponse bulkResponse = esUtil.getESClient().bulk(builder -> {
                for (Product product : products) {
                    builder.index(PRODUCT_INDEX)
                            .operations(ob -> {
                                ob.index(ib -> ib.document(product).pipeline("score").id(product.getId())));
                                return ob;
                            });
                }
                return builder;
            });

CodePudding user response:

You can use Fluent DSL like below as mentioned here:

List<Product> products = fetchProducts();

BulkRequest.Builder br = new BulkRequest.Builder();

for (Product product : products) {
    br.operations(op -> op           
        .index(idx -> idx            
            .index("products")       
            .id(product.getSku())
            .document(product)
        )
    );
}

BulkResponse result = esClient.bulk(br.build());

You can use Classic Builder like below (Not Recommndate):

IndexRequest.Builder<Product> indexReqBuilder = new IndexRequest.Builder<>();
indexReqBuilder.index("product");
indexReqBuilder.id("id");
indexReqBuilder.document(product);
        
List<BulkOperation> list = new ArrayList<BulkOperation>();
list.add(indexReqBuilder);
        
BulkRequest.Builder br = new BulkRequest.Builder();
br.index("");
br.operations(list);
        
client.bulk(br.build());
  • Related