弹性搜索批量更新使用python,如何用新数据附加数组字段

2024-09-24 22:24:56 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在python中使用bulkupdate更新弹性搜索中的字段。我尝试了很多方法,但都是错误的。在某些情况下,我会遇到文档丢失错误,如何同时更新和升级。另外,附加到字段也不起作用。elasticsearch==7.9.1是我在python中使用的包

for i in range(0, length, steps):
    end_index = length-1 if i+steps>length else i+steps
    temp_list = test_data[i: end_index]
    bulk_file = ''
    actions = [{
        "_index": "test-data",
        "_opt_type":"update",
        "_type": "test-test-data",
        "_id": test_row ['testId'],
        "doc":{"script": {
                          "source": "ctx._source.DataIds.add(params.DataIds)",
                          "lang": "painless",
                          "params": {
                              "DataIds":test_row ['DataIds']
                          }
                      }}
        }
        for test_row in temp_list
    ]
    helpers.bulk(es, actions)

我得到的错误是什么

    {'update': {'_index': 'test-data', '_type': 'products', '_id': '333', 'status': 400, 'error': {'type': 'illegal_argument_exception', 'reason': 'failed
 to execute script', 'caused_by': {'type': 'script_exception', 'reason': 'runtime error', 'script_stack': ['ctx._source.dataIds.add(params.dataIds)', '
    ^---- HERE'], 'script': 'if (ctx._source.dataIds == null) { ctx._source.dataIds = []; } ctx._source.dataIds.add(params.dataIds)', 'lang': 'painless', 'position': {'offse
t': 105, 'start': 71, 'end': 118}, 'caused_by': {'type': 'illegal_argument_exception', 'reason': 'dynamic method [java.lang.String, add/1] not found'}}}, 'data': {'upsert': {}, 'scripted_up
sert': True, 'script': {'source': 'if (ctx._source.dataIds == null) { ctx._source.dataIds = []; } ctx._source.dataIds.add(params.dataIds)', 'lang': 'painless', 'params': {'c
dataIds': 'set123'}}}}}])

Tags: testaddsourcelangdataindextype错误
1条回答
网友
1楼 · 发布于 2024-09-24 22:24:56

^{} via script的正确方法是不使用doc,而只使用script部分。如果要在同一命令中upsert和update,还需要upsert部分。事情是这样的:

actions = [{
    "_op_type":"update",
    "_index": "test-data",
    "_type": "test-test-data",
    "_id": test_row ['testId'],
    "upsert": {
       "DataIds": test_row ['DataIds']
    },
    "script": {
        "source": "ctx._source.DataIds.add(params.DataIds)",
        "lang": "painless",
        "params": {
           "DataIds":test_row ['DataIds']
        }
    }
} for test_row in temp_list
]

另一种方法是使用^{}

actions = [{
    "_op_type":"update",
    "_index": "test-data",
    "_type": "test-test-data",
    "_id": test_row ['testId'],
    "upsert": {},
    "scripted_upsert": true,
    "script": {
        "source": "if (ctx._source.DataIds == null) { ctx._source.DataIds = []; } ctx._source.DataIds.add(params.DataIds)",
        "lang": "painless",
        "params": {
           "DataIds":test_row ['DataIds']
        }
    }
} for test_row in temp_list
]

相关问题 更多 >