使用python附加到现有的elasticsearch数组字段

时间:2016-01-11 18:42:04

标签: python elasticsearch

我有以下ES对象:

    {
      "_index": "index_name",
      "_type": "my_type",
      "_id": "12345678-abcd-9012-efgh-3456ijkl7890"
      "_source": {
        "apps": [
          {
            "processName": "process_name_1",
            "name": "app_name_1",
            "VersionName": "version_1"
          },
          {
            "processName": "process_name_2",
            "name": "app_name_2",
            "VersionName": "version_2"
          }
        ]
      }
    }

我想在" apps"中添加另一个对象数组,同时保留现有数据,如下所示:

    {
      "_index": "index_name",
      "_type": "my_type",
      "_id": "12345678-abcd-9012-efgh-3456ijkl7890"
      "_source": {
        "apps": [
          {
            "processName": "process_name_1",
            "name": "app_name_1",
            "VersionName": "version_1"
          },
          {
            "processName": "process_name_2",
            "name": "app_name_2",
            "VersionName": "version_2"
          },
          {
            "processName": "process_name_3",
            "name": "app_name_3",
            "VersionName": "version_3"
          }
        ]
      }
    }

如您所见,我只添加了第三个应用程序"这些应用程序对象。我需要使用elasticsearch模块在Python中执行此操作。我的所有尝试都会覆盖现有项目或不起作用。我尝试使用" ctx._source.apps + = newapps"脚本,但使用Python,它似乎只是附加一个名为"脚本"的新对象。和新的数据,以及" apps"对象,而不是仅仅添加到" apps"宾语。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

这样的东西应该可行,你可以参考update api获取python以获取更多信息。您需要将script放在body param

from elasticsearch import Elasticsearch

es = Elasticsearch()

es.update(
    index="index_name",
    doc_type="my_type",
    id="12345678-abcd-9012-efgh-3456ijkl7890",
    body={"script": "ctx._source.apps += app",
          "params": {
              "app": {
                  "processName": "process_3",
                  "name": "name_3",
                  "VersionName": "version_3"
              }
            }
          }
)