0

I would like to add a set of key value pairs from a HashMap to the request body of the UpdateRequest function in Elastic Search's Java High Level REST client API.

I can successfully loop through the HashMap and pull out the keys and values. How can I add these to the builder in a clean and efficient way? The

updated: new Date(), animal: crocodile

code is a placeholder for what I would like to achieve with our real data from the HashMap.

Here is the documentation I have been using from Elastic Search. We are using version 7.5.2.

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-document-update.html

public void updateDocument(@PathParam("index_name") String index_name,
        @PathParam("document_id") String document_id, HashMap<String, String> columnValues) throws IOException {
    RestHighLevelClient client = createHighLevelRestClient();
    Set<String> keys = columnValues.keySet();
    for (String key : keys) {
        System.out.println(key);
        System.out.println(columnValues.get(key));
    }
    XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    {
        builder.timeField("updated", new Date());
        builder.field("animal", "crocodile");
    }
    builder.endObject();
    UpdateRequest request = new UpdateRequest(
            index_name, document_id);
    request.docAsUpsert(true).doc(builder);
    UpdateResponse updateResponse = client.update(
            request, RequestOptions.DEFAULT);
    System.out.println(updateResponse);
    client.close();
GNG
  • 1,341
  • 2
  • 23
  • 50

1 Answers1

0

This works...

        XContentBuilder builder = XContentFactory.jsonBuilder();
    builder.startObject();
    for (String key : keys) {
        System.out.println(key);
        System.out.println(columnValues.get(key));
        builder.field(key, columnValues.get(key));
    }
    builder.endObject();
GNG
  • 1,341
  • 2
  • 23
  • 50