在弹性搜索中轻松检索数组最后一个元素的信息

Retrieve information of last element of an array painless-ly in elasticsearch

在更新文档时(使用更新 API),我需要提取最后输入的数组元素的字段,然后在向同一数组添加新元素时使用它。

例如:

{
  "_id": "guid",
  "timestamp": "time",
  "conversation": [
    {
      "previousTopic": "A",
      "currentTopic": "B",
      "score": 80
    },
    {
      "previousTopic": "B",
      "currentTopic": "C",
      "score": 85
    }
  ]
}

现在,在使用更新 API 向该数组插入新元素时,首先提取最后一个元素(在本例中为 C)的 "currentTopic" 字段,然后将其插入为"previousTopic" 下一个元素。

我知道如何使用基本更新 API,它会向文档的数组中插入一个新元素:

POST test/_doc/{doc_id}/_update
{
    "script" : {
        "source": "ctx._source.communication.add(params.newcom)",
        "lang": "painless",
        "params" : {
          "newcomm" : {
          "previousTopic": {extracted value will go here}
          "currentTopic" : "D"
          "score" : 89 }
        }
    }
}

我能够使用无痛脚本完美地做到这一点。

POST test/_doc/nbsadmnsabdmas/_update
{
    "script" : {
        "lang": "painless",
        "source" : 
        """
        // find the length of array 
        def count = ctx._source.conversation.length;

        // get to the last element and extract
        def temp = ctx._source.conversation[count-1].currentTopic;

        // add a new element to the array
        ctx._source.communication.add(['previousTopic':temp,'currentTopic':'D',
         'score':90]);

        """
    }
}