Search code examples
elasticsearchappendsense

Append to array in Elasticsearch


I am currently struggling a bit on how to append a value to an array in elasticsearch.

The Document looks something like this:

  {
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "iethreads",
        "_type": "thread",
        "_id": "AVRk6WRMU5h_y_zwo4s0",
        "_score": 1,
        "fields": {
          "links": [
            "[\"https://somelink123.net/thread-714222&page=1\", \"https://somelink123.net/thread-714222&page=2\", \"https://somelink123.net/thread-714222&page=3\", \"https://somelink123.net/thread-714222&page=4\"]"
          ]
        }
      }
    ]
  }
}

then I run the following update query

POST _update
{
  "script" : "ctx._source.links+=new_posts",
  "params" : {
    "new_posts":"blabliblub"
  }
}

and I get this:

{
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 1,
    "hits": [
      {
        "_index": "iethreads",
        "_type": "thread",
        "_id": "AVRk6WRMU5h_y_zwo4s0",
        "_score": 1,
        "fields": {
          "links": [
            "[\"https://somelink123.net/thread-714222&page=1\", \"https://somelink123.net/thread-714222&page=2\", \"https://somelink123.net/thread-714222&page=3\", \"https://somelink123.net/thread-714222&page=4\"]blabliblub"
          ]
        }
      }
    ]
  }
}

So for me this looks like the array is treated like a string and it just appends the string - this is not what I want.

How would I append the "blabliblub" as a new element to the array ?


Solution

  • It seems your links field actually has one element as string instead of an array. To your update be succesful, your structure must be like that:

    "fields": {
          "links": [
            "https://somelink123.net/thread-714222&page=1", 
            "https://somelink123.net/thread-714222&page=2",
            "https://somelink123.net/thread-714222&page=3", 
            "https://somelink123.net/thread-714222&page=4"
          ]
        }