How to upadate value with java api without merging it, and only append that's not same

Excuse me Sir, I’am still new in elastic, I use java as client, I have a problem that how to update data without merging it, and if the data is there, it did’nt update it,,but increase/append it, and if data is same, it did’nt append again, so there is no multiple with same value,this is the simple example

this is my Food.java
<
private string id
private string name
private string alias

public String getId() {
return Id;
}

public void setId(String Id) {
    this.Id = Id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String[] getAlias() {
	return alias;
}

public void setAlias(String[] alias) {
    this.alias = alias;
}

/>

this is my FoodController.java
<
@PutMapping("/upsert/{id}")
public String upsert(@PathVariable final String id, @RequestBody Food food) throws IOException {
try {
IndexRequest indexRequest = new IndexRequest("foods", "foodtype", id)
.source(jsonBuilder()
.startObject()
.field("name", food.getName())
.field("alias", food.getAlias())
.endObject());
UpdateRequest updateRequest = new UpdateRequest("foods", "foodtype", id)
.doc(jsonBuilder()
.startObject()
.field("name", food.getName())
.field("alias", food.getAlias())
.endObject())
.upsert(indexRequest);
client.update(updateRequest).get();
System.out.println(client.update(updateRequest).get().status());
return client.update(updateRequest).get().status().toString();
} catch (InterruptedException | ExecutionException e){
System.out.println(e);
}
return "Exception";
}
/>

So how to update it with java api?, if I have the data like this
<
{
“name”:”ChikenCheese”,
“alias”: [“CC”,”CCK”,”CCKH”]
}
/>

and when I send with PUT method from request body with this
<
{
“alias”: [“CC”,”CCK”,”CCCBBB”]
}
/>

it will be like this
<
{
“name”:”ChikenCheese”,
“alias”: [“CC”,”CCK”,”CCKH”,”CCCBBB”]
}
/>

it only append to "alias" that is not same, and the name is not changed to null, i’am sorry for a long question.

You can't do that.

Either you provide the new version of the full document and use index API, either you provide a new version of some fields and use the update API.

You can't provide a sub part of a field and expect it to be merged with existing values for this field.

So this is something you need to solve in your application by running a GET of the full document the update it in your application and the send it back entirely to elasticsearch with the index API.

1 Like

Thank you sir for your fast respons, i'll try it

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.