javaelasticsearchelasticsearch-dslelasticsearch-java-apielasticsearch-java-api-client

Update of a record in elastic using elastic 8.7 javaclient


I attempted to add a couple new fields to an existing record in elastic search. The record is being updated, however all previously indexed fields have been cleared.

Is there something am I doing wrong?

Maven dependency

<dependency>
   <groupId>co.elastic.clients</groupId>
   <artifactId>elasticsearch-java</artifactId>
   <version>8.7.1</version>
</dependency>

Me code:

RestClientBuilder builder = RestClient.builder(new HttpHost(esIP, Integer.parseInt(esPort)));

RestClient restClient = builder.build();

//jsonMap indecates one record to be indexed 

br.operations(op -> op.index(idx -> idx.index((String) jsonMap.get("index_name")).id(jsonMap.get("id").toString()).document(jsonMap)));

Solution

  • Try following, you shoud exclude meta data (like index, id) from doc param.

        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)).build();
    
        // Create the transport with a Jackson mapper
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
    
        // And create the API client
        ElasticsearchClient client = new ElasticsearchClient(transport);
    
    
        HashMap jsonMap = new HashMap();
        jsonMap.put("field", "new value");
    
        UpdateRequest.Builder builder = new UpdateRequest.Builder();
        builder.index("index_name")
                .id("id")
                .doc(jsonMap); // exclude meta data (like index, id)
    
        UpdateResponse response = client.update(builder.build(), Object.class);
    
        System.out.println("Indexed with version " + response.version());