Elasticsearch Insert single key if not exists, without affecting other keys

2.1k views Asked by At

In some of my documents, I have a key present as school. Say the document is:

{
    "id" : "123",
    "name" : "Robert",
    "school" : "Public"
}

Now, school is not present in all documents. I want to insert school key in all documents where it is not already present with a default String.

I am using Elasticsearch version number 2.4.5. How can I do it? Am I looking at a bulk update?

1

There are 1 answers

5
Val On BEST ANSWER

I would clearly use the update by query API for this. You can search for all documents that don't have the school field and set it to whatever default value you wish:

POST your-index/your-type/_update_by_query
{
  "query": {
    "bool": {
      "must_not": {
        "exists": {
          "field": "school"
        }
      }
    }
  },
  "script": {
    "inline": "ctx._source.school = 'dummy'"
  }
}

Note that you need to enable dynamic scripting and restart your ES server.