How can I overwrite a list field of strings in Spring ElasticSearch?

Viewed 258

I am working with the Spring data library for ElasticSearch. I have an ES document looking like the following:

@Getter
@Setter
@Document(indexName = "my_ideas")
public class MyIdea {
    @Id
    @Field(type = FieldType.Long)
    private Long id;

    @Field(type = FieldType.Text)
    private List<String> countries;

    // ... more fields
}

I have an API endpoint which accepts a new list of countries. My goal is to simply overwrite the list of countries in the above ES document. To do this, I use:

@Autowired
ElasticsearchOperations esRestTemplate;

SearchHits<MyIdea> hits = esRestTemplate.search(searchQuery, MyIdea.class);
MyIdea ideaDoc = hits.getSearchHits().stream().findFirst().orElse(null).getContent();
// call method to update the countries
esRestTemplate.save(ideaDoc);

That is, I simply overwrite the list of countries on the document with something else. I assumed that ES' #save() method would behave similarly to the one for JPA. The expected behavior was that, logically, the previous country list would be deleted, and the one I pass in would be the replacement. To my surprise, what I observed is that the countries in the list of the above document were added, while retaining the values which were already there. So, assuming the document started off with "America" and "Canada" in the list, and I passed in "Singapore," the list would in fact contain all three countries after the call to #save().

Can someone expert in ElasticSearch for Spring point out where I am going wrong here?

1 Answers

After some careful investigation, it turns out that the source object being used to populate the ElasticSearch document had some duplicate data in it. At least, duplicate data was being copied over to the ES document. Once I resolved this, the problem went away. So Spring ElasticSearch's #save() is working as expected, and it knows how to either insert or update an ES document.

Related