Update of a record in elastic using elastic 8.7 javaclient

huangapple go评论72阅读模式
英文:

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>

My code:

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

RestClient restClient = builder.build();

// jsonMap indicates 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)));
英文:

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

&lt;dependency&gt;
   &lt;groupId&gt;co.elastic.clients&lt;/groupId&gt;
   &lt;artifactId&gt;elasticsearch-java&lt;/artifactId&gt;
   &lt;version&gt;8.7.1&lt;/version&gt;
&lt;/dependency&gt;

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 -&gt; op.index(idx -&gt; idx.index((String) jsonMap.get(&quot;index_name&quot;)).id(jsonMap.get(&quot;id&quot;).toString()).document(jsonMap)));

答案1

得分: 0

Here's the translated code part without the comments:

RestClient restClient = RestClient.builder(
    new HttpHost("localhost", 9200)).build();

ElasticsearchTransport transport = new RestClientTransport(
    restClient, new JacksonJsonpMapper());

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);

UpdateResponse response = client.update(builder.build(), Object.class);

System.out.println("Indexed with version " + response.version());
英文:

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

    RestClient restClient = RestClient.builder(
            new HttpHost(&quot;localhost&quot;, 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(&quot;field&quot;, &quot;new value&quot;);

    UpdateRequest.Builder builder = new UpdateRequest.Builder();
    builder.index(&quot;index_name&quot;)
            .id(&quot;id&quot;)
            .doc(jsonMap); // exclude meta data (like index, id)

    UpdateResponse response = client.update(builder.build(), Object.class);

    System.out.println(&quot;Indexed with version &quot; + response.version());

答案2

得分: 0

以下是您提供的代码的中文翻译:

public class ElasticLowLevelRemote {
    public static void main(String[] args) throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("输入索引:");
        String indexInput = input.nextLine();
        System.out.print("输入 ID:");
        String id = input.nextLine();
        RestClient restClient = RestClient.builder(
            new HttpHost("IP地址", 端口, "http"))
            .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(
                new BasicCredentialsProvider() {{
                    setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials("用户名", "密码"));
                }})).build();
        HttpEntity entity = new NStringEntity("{" +
            "\n \"query\": {" +
            "\n \"match\": {" +
            "\n \"_id\": \"" + id + "\"" +
            "\n }" +
            "\n }" +
            "}",
            ContentType.APPLICATION_JSON);
        Response response = restClient.performRequest(
            "GET", "/" + indexInput + "/_search",
            Collections.emptyMap(),
            entity);

        String jsonResponse = EntityUtils.toString(response.getEntity());
        ObjectMapper mapper = new ObjectMapper();
        Object json = mapper.readValue(jsonResponse, Object.class);
        String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

        System.out.println(formattedJson);

        restClient.close();
    }
}

希望这对您有所帮助。如果您有任何其他问题,请随时提出。

英文:

So you are developing low level client. And as your provided source code is not full enough to understand, I'm giving a sample Low Level Rest API over Remote Elasticsearch:

public class ElasticLowLevelRemote {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print(&quot;enter index &quot;);
String indexInput = input.nextLine();
System.out.print(&quot;enter id &quot;);
String id = input.nextLine();
RestClient restClient = RestClient.builder(
new HttpHost(&quot;ipaddress&quot;, port, &quot;http&quot;))
.setHttpClientConfigCallback(httpClientBuilder -&gt; httpClientBuilder.setDefaultCredentialsProvider(
new BasicCredentialsProvider() {{
setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(&quot;username&quot;, &quot;password&quot;));}})).build();
HttpEntity entity = new NStringEntity(&quot;{\n \&quot;query\&quot;: {\n \&quot;match\&quot;: {\n \&quot;_id\&quot;: \&quot;&quot; + id + &quot;\&quot;\n }\n }\n}&quot;,
ContentType.APPLICATION_JSON);
Response response = restClient.performRequest(
&quot;GET&quot;, &quot;/&quot;+indexInput+&quot;/_search&quot;,
Collections.emptyMap(),
entity);
String jsonResponse = EntityUtils.toString(response.getEntity());
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(jsonResponse, Object.class);
String formattedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
System.out.println(formattedJson);
restClient.close();
}
}

huangapple
  • 本文由 发表于 2023年5月13日 23:13:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76243449.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定