如何使用 elasticsearch-py 附加到 Elasticsearch 中的数组

How to append to an array in Elasticsearch using elasticsearch-py

使用官方ElasticSearch Python library (Docs)

我创建了一个索引:

doc = {
    "something": "123a",
    "somethingelse": "456b",
    "timestamp": datetime.now(),
    "history": []
}
es.index(index="someindex", doc_type="somedoctype", id="someid", body=doc)

我想每次都将项目附加到历史记录中,而不是覆盖它们:

es.update(index="someindex", doc_type="somedoctype", id="someid",
          body={"doc": {
                "history": {
                    "123abc": "abc", "456def": "def", "timestamp": datetime.now()
                }
               }
          })

我必须在第二个代码片段中更改什么才能使其附加到历史记录 array/list 而不是每次都覆盖它?

您可以在 elasticsearch 中使用 scripted updates。要附加到数组,请尝试这样的操作:

es.update(index="someindex", doc_type="somedoctype", id="someid",
      body={
         "script" : {
             "source": "ctx._source.history.addAll(params.history)",
             "lang": "painless",
             "params" : {
                 "history" : ["item1","item2"]
             }
         }
      })