Home > Net >  Elasticsearch appends object fields on update instead of overwriting
Elasticsearch appends object fields on update instead of overwriting

Time:04-18

I have an object in Elasticsearch which may contain different fields. In my app this object is Enum so it can't actually contain more than one field at the same time. But when i do an update in Elasticsearch - it appends the fields instead of overwriting the whole object.

For example - the document may be public or accessible only to a group of users:

POST _template/test_template
{
  "index_patterns": [
    "test*"
  ],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "_source": {
        "enabled": true
      },
      "properties": {
        "id": {
          "type": "keyword"
        },
        "users": {
          "type": "object",
          "properties": {
            "permitted": {
              "type": "keyword"
            },
            "public": {
              "type": "boolean"
            }
          }
        }
      }
    }
  },
   "aliases" : {
      "test-alias" : { }
    }
}

POST test_doc/_doc/1
{
  "id": "1",
    "users": {
      "permitted": [
        "1", "2"
      ]
    }
}

POST _bulk
{"update":{"_index":"test_doc","_type":"_doc","_id":1}}
{"doc":{"id":"1","users":{"public": true}},"doc_as_upsert":true}

GET test-alias/_search

I am expecting this result:

{
    "id": "1",
    "users": {
        "public": true
    }
}

But the actual result is:

{
    "id": "1",
    "users": {
        "permitted": [
            "1",
            "2"
        ],
        "public": true
    }
}

At the same time it overwrites the fields with the same name perfectly (i can change the permitted array or public field to false). How do you disable object fields appending?

CodePudding user response:

You need to change the action in bulk request to index from update, correct request would be

{"index":{"_index":"71908768","_id":1}}
{"doc":{"id":"1","users":{"public": true}}}

refer actions and what they do in details in the official Elasticsearch docs. In short, update partially updates the document, while index action Indexes the specified document. If the document exists, replaces the document and increments the version.

  • Related