0

All of our ElasticSearch documents contain a field called Categories which contains a string of comma-separated values. The length of each value between the commas is 5 characters, and the field can be anywhere from 1 to 12 5-character values.

I need to run a query against the index which says append ,ABCDE to the end of Categories field of all documents, unless the field already contains the value ABCDE in it, in which case do not append anything to the field.

1 Answer 1

2

You can use ElasticSearch _update_by_query like below

POST my_index/my_type/_update_by_query
{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "Categories": "ABCDE"
          }
        }
      ]
    }
  },
  "script": {
    "inline": "ctx._source.Categories += ', ABCDE'",
    "lang": "painless"
  }
}

The above query will append string ', ABCDE' to Categories if Categories doesn't contains the term ABCDE

Sign up to request clarification or add additional context in comments.

8 Comments

Many thanks Ashraful. Just to be sure I understand, the first part of the query syntax will look for Categories to contain 12345 anywhere in the string, and not just for where Categories = 12345?
@Stpete111 match query will look if the term 12345 contains in the Categories and since match is inside must_not, it will look for must not contains the term 12345 in Categories
Ashraful, just to verify the results, I have run just the search part of your query, but I changed must_not to must as I wanted to confirm that results which contain ABCDE are included in the results. However, when I run it, it only brings back results where Categories equal ABCDE exactly. Is this expected behavior?
@Stpete111 what is field type of Categories ? text or keyword ?
@Stpete111 text type uses standard tokenizer which provides grammar based tokenization (based on the Unicode Text Segmentation algorithm. i.e if categories contains text The 2 QUICK Brown-Foxes jumped over the lazy dog's bone it will be tokenized into [The, 2, QUICK, Brown, Foxes, jumpe, d, over, the, lazy, dog's, bone] So this catgories will be match if any of the tokens provided in the match query
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.