Search code examples
elasticsearchnest

how to add multiple tags to an existing list using script in ElasticSearch


I have document with "tags" as one property which has list of values. For example

"tags": [ "red", "blue", "green"]

I want to add ["yellow", "black"] and remove ["blue"] tags in one update call in NEST.

And how do I ensure all tags in that list are unique.

Note: I'm using ElasticSearch 6.x

Thanks


Solution

  • You essentially have two options:

    1. Get the document from Elasticsearch and deserialize into a type that models the tag collection as a HashSet<string> (or perform the distinct operation of tags yourself).

      Add the new tags to the collection

      Index the type back into Elasticsearch using the same index, id (and type) to overwrite the existing document.

    or

    1. Perform a scripted update with a scripting language (most likely Painless), to add only distinct tags to the document. The Getting and indexing of the document still occurs, but within Elasticsearch.