1

I am using Elastic Search 5.6 and I'd like to add a new field to an existing document. This field's value should be of type array. I was able to add a new field with an array of strings by sending a POST request with the following body

{"script" : "ctx._source.new_field = ['string1', 'string2']"}

to my endpoint

http://localhost:9200/my_index/my_mapping/item_173969/_update

and verified that the new field is there, but I need to set the value of this key to an array of objects instead. How can I do this? Specifically, I need my document to have:

"size": [
    {
        "item_size": "XL",
        "country_size": "US"
    }
]
1
  • please remember to mark the answer as correct if it was useful for your problem or let me know if you need anything else Commented Mar 4, 2021 at 18:15

1 Answer 1

4

You are almost there. I'm using ES 7.1 that ignores document type but the script part should work.

Ingesting data

PUT test_david/_doc/1
{
  "name": "doc1"
}

Updating document

POST test_david/_update/1
{
  "script": {
    "source":  "if (!ctx._source.containsKey('sizes')) ctx._source.sizes= new ArrayList(); ctx._source.sizes.add(params.data);",
    "params": {
      "data": {
        "item_size": "XL",
        "country_size": "US"
      }
    }
  }
}

Note this will validate the document has the property sizes already created and add a new size to it.

Query

POST test_david/_search

Response

{
  "took" : 1,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "test_david",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "doc1",
          "sizes" : [
            {
              "country_size" : "US",
              "item_size" : "XL"
            }
          ]
        }
      }
    ]
  }
}

About Nested Type

You use nested type only if you want to preserve the relationship between properties of the same children to make queries.

Object field type let to do searches like:

"item_size and/or item_country on any of the size objects"

Nested field type searches like:

"item_size and/or item_country on the same size object"

Not all nested fields needs to be of nested type. Only if you need to keep the relation between properties of the same children to do queries because nested type is more expensive and if you are only storing and displaying data it makes no sense to use this type of field.

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

Comments

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.