Private
Private

Reputation: 1761

Is it possible to update to a document with array of fields in elasticsearch using update_by_query API?

I have a document with the following content in all the documents in an index:

   "universities": {
                      "number": 1,
                      "state": [
                         {
                            "Name": "michigan",
                            "country": "us",
                            "code": 5696
                         }
                      ]
                   }

I want to update all the documents in the index like this

  "universities": {
                      "number": 1,
                      "state": [
                         {
                            "Name": "michigan",
                            "country": "us",
                            "code": 5696
                         },                          
                         {
                            "Name": "seatle",
                            "country": "us",
                            "code": 5695
                         }
                      ]
                   }

IS this can be possible using update_by_query in elasticsearch 2.4.1?

I tried the below query:

"script": {
    "inline": "for(i in ctx._source.univeristies.state){i.name=Text}",
    "params": {
      "Text": "seatle"
    }
  }
}

but is appending the name to existing one rather than creating a new one in a list.

Upvotes: 1

Views: 3130

Answers (1)

Val
Val

Reputation: 217254

You need to use this script instead:

"script": {
    "inline": "ctx._source.universities.state.add(new_state)",
    "params": {
      "new_state": {
          "Text": "Seattle",
          "country": "us",
          "code": 5695
      }
    }
  }
}

UPDATE:

For later versions of ES (6+), the query looks like this instead:

"script": {
    "source": "ctx._source.universities.state.add(params.new_state)",
    "params": {
      "new_state": {
          "Text": "Seattle",
          "country": "us",
          "code": 5695
      }
    }
  }
}

Upvotes: 3

Related Questions