Create bulkRequest using latest java API client(8.1.1) for list of products using builder lambda method

I am having a list of Products(for simplicity let's assume it has an id, brand, and name properties), and I want to index this list of products to Elasticsearch using java API client version 8.1.1.

BulkRequest in java api-client, accepts a List, that makes sense and there are three different overloaded methods to pass the list of bulkoperations, like below

Using lambda builder

 /**
         * Required - Request body.
         * <p>
         * API name: {@code _value_body}
         * <p>
         * Adds a value to <code>operations</code> using a builder lambda.
         */
        public final Builder operations(Function<BulkOperation.Builder, ObjectBuilder<BulkOperation>> fn) {
            return operations(fn.apply(new BulkOperation.Builder()).build());
        }

And using List

 public final Builder operations(List<BulkOperation> list) {
            this.operations = _listAddAll(this.operations, list);
            return this;
        }

I was able to bulk index my products using the second simple method that accepts list but not able to do the same using the builder lambda which is preferred as it would be more concise and more readable.

P.S-> created this post on Stackoverflow but no luck so far.

Hey,

take a look at GitHub - spinscale/elasticsearch-rest-client-samples: Elasticsearch REST client samples using Testcontainers - my sample repo using the new Elasticsearch Java Client. There is a snippet using bulk at elasticsearch-rest-client-samples/ProductServiceImpl.java at main · spinscale/elasticsearch-rest-client-samples · GitHub

Hope this helps!

--Alex

Thanks @spinscale your code is doing exactly what I need, but I have few questions,

I am using my own class named as ElasticsearchClient, which uses the Elasticsearch provided API client, and there I defined bulkRequest using below method signature, to make sure that call to Elasticsearch is in a single class and not spread across my application.

public BulkResponse bulkIndex(BulkRequest request) {
         esClient.bulk(request);
        // Do other stuff 
}

Now, as you can see this method accepts the BulkRequest object and not the builder, and your method is directly calling the bulk with the builder lambda, I tried creating the bulkRequest using your code, but couldn't do it.

  1. Can we get rid of foreach and use the stream on products?

@spinscale How are you? Did you get a chance to look at my previous reply.

Hey,

I'm sorry, but I cannot make too much out of that question. That does not look like a client implementation detail to me, but rather like implementing a proper abstraction in your java code.

Please try to rephrase your question, and I hope understand then :slight_smile:

Thanks!

--Alex

Thanks @spinscale , I would explain it in detail shortly..

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.