jpganz18
jpganz18

Reputation: 5858

How to update an entry on Elastic Search using Java client

I am trying to make an update on my es model information using an elastic search client

org.elasticsearch.client.Client

https://www.programcreek.com/java-api-examples/?api=org.elasticsearch.client.Client

It is really hard for me to find the correct way to do it since I dont know the index and the matcher, Im sorry, I am very beginer at this subject.

  {
    "_index": "my_index_20",
    "_type": "student",
    "_id": "a80ae58",
    "_source": {
      "model": {
        "id": "a80ae58748e",
        "name": "John Doe"
        ....

My code so far

 response = esClient.prepareUpdate("student", "name", "John Doe")
                    .setDoc(jsonBuilder()               
                    .startObject()
                    .field("name", "Joe Doe")
                    .endObject())
                    .get();

Am I using the right index? or what could I change here?

I am not getting any error but a "document missing" result... means I might not be using the right indexes.

Ideas?

Updated according feedback and more info...

I moved it to

response = esClient.prepareUpdate("my_index_20", "student", "a80ae58")
                    .setDoc(jsonBuilder()               
                    .startObject()
                    .field("name", "Joe Doe")
                    .endObject())
                    .get();

This works but since I dont know the index ID I cannot perform this, is there any way to do it by a query builder or other functionality?

Upvotes: 4

Views: 2092

Answers (1)

Lazcool
Lazcool

Reputation: 63

This is the signature of the prepareUpdate method:

UpdateRequestBuilder prepareUpdate(String index, String type, String id);

So the correct syntax may be

esClient.prepareUpdate("my_index_20", "student", "a80ae58").setDoc(...)...

If you want to do it by matching other field, use the update by query.

String indexName = "my_index_*"; //Assuming that you don't know the exact index, but know the global format (for example the beginning of the name of the index)
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.filter(QueryBuilders.termQuery("name", "John Doe"));
boolQuery.filter(QueryBuilders.termQuery("otherField", "otherFieldValue"));
UpdateByQueryRequestBuilder updateByQuery = UpdateByQueryAction.INSTANCE.newRequestBuilder(esClient);
updateByQuery.source(indexName); 
updateByQuery.filter(boolQuery); 
BulkByScrollResponse updateResponse = updateByQuery.get();

Upvotes: 2

Related Questions