Search code examples
javaelasticsearchelasticsearch-java-api

Elasticsearch Update indexdocument


I need to update an index document for an elasticsearch table and this is the code I have implemented. But it is not working, what's wrong and how should I implement this?

My code.

Map<String, Object> matching_result;
for (SearchHit hit : response_text.getHits()) {
    matching_result = hit.getSource();
    String flag_value = matching_result.get("flag").toString();
    matching_result.put("flag", true);
}

String indexString = JSONConverter.toJsonString(matching_result);

IndexResponse response = client.prepareIndex("index_name", "data").setSource(indexString).execute().actionGet();
boolean created = response.isCreated();
System.out.println("created or updated--------------------->" + created);
System.out.println("flag value==========" + matching_result.get("flag"));
return actual_theme;

(JSONConverter.toJsonString) is our library class for converting to json string. What is wrong with this query? Instead of updating the existing document it is creating a new one. I want to change the existing one.


Solution

  • Based on your example code, it looks like by "update" you mean you are trying to replace the entire document. In order to do this, you must specify the id of the document you wish to update.

    Using the Java API, in addition to calling setSource on the IndexRequestBuilder, you would also need to supply the id by calling setId. For example:

    IndexResponse response = client.prepareIndex("index_name", "data")
      .setSource(indexString)
      .setId(123)    <----- supply the ID of the document you want to replace
      .execute()
      .actionGet();
    

    Otherwise, just so you know, in ES you have the option to do a partial update. That is, only update certain fields in the document. This can be done with a script or by providing a partial document. Have a look at the documentation for the Update API.

    In either case, you need to provide ES with the ID for the document you wish to modify.