karthikdivi
karthikdivi

Reputation: 3643

Can we pass Java Pojo to Elasticsearch Index API using new REST Client

I am going through the new Elasticsearch's Java REST client and looking at different ways to index a document ( here https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high-document-index.html )

Is there any possibility where I can pass my Java Pojo to Index? like following

IndexRequest request = new IndexRequest("posts"); 
request.id("1"); 
request.source(new User("1", "Foo", 22, new Date()));
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

Upvotes: 1

Views: 2534

Answers (2)

Bilal Demir
Bilal Demir

Reputation: 686

If you are using RestHighLevelClient version 7.x, you can pass a POJO with simple mapping like:

IndexRequest request = new IndexRequest("posts");
request.id("1");
request.source(new ObjectMapper().writeValueAsString(new User("1", "Foo", 22, new Date())), XContentType.JSON);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

Upvotes: 0

Val
Val

Reputation: 217464

No, you cannot pass a POJO directly to the IndexRequest.source() method, you need to either pass:

  1. a JSON string
  2. a Map
  3. a Jackson serialized POJO
  4. an object created via a provided helper

In your case, I guess the 3rd option could make more sense since you have a POJO at hand.

Upvotes: 2

Related Questions