You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python操作Elasticsearch添加字段遇编译错误,如何解决?

Elasticsearch批量更新字段报错及版本冲突问题

我正在用Python处理一个包含120亿文档的Elasticsearch索引,需要给每个文档添加direction字段:该字段会根据src字段的不同值赋值为"e",同时特定_id为"YKReAoQBk7dLIXMBhYBF"的文档也需要设为"e"。我写了如下代码:

from elasticsearch import Elasticsearch
es = Elasticsearch(["https://myESserver:9200"],
                   http_auth=('myUsername', 'myPassword'))

query_to_add_direction_field = {
    "script": {
        "inline": "direction=\"e\"",
        "lang": "painless"
    },
    "query": {"constant_score": {
        "filter": {"bool": {"must": [{"match": {"_id": "YKReAoQBk7dLIXMBhYBF"}}]}}}}
}

results = es.update_by_query(index="myIndex-*", body=query_to_add_direction_field)

运行后出现报错:

elasticsearch.BadRequestError: BadRequestError(400, 'script_exception', 'compile error')

我是Elasticsearch新手,请问怎么修正这个查询避免报错?


更新:

我把代码改成了下面这样:

query_find_id = {
    "size": "1",
    "query": {
        "bool": {
            "filter": {
                "term": {
                    "_id": "YKReAoQBk7dLIXMBhYBF"
                }
            }
        }
    }
}
query_to_add_direction_field = {
    "script": {
        "source": "ctx._source['egress'] = true",
        "lang": "painless"
    },
    "query": {
        "bool": {
            "filter": {
                "term": {
                    "_id": "YKReAoQBk7dLIXMBhYBF"
                }
            }
        }
    }
}

results = es.search(index="traffic-*", body=query_find_id)
results = es.update_by_query(index="traffic-*", body=query_to_add_direction_field)
results_after_update = es.search(index="traffic-*", body=query_find_id)

现在代码第一次运行没报错,我以为问题解决了,但再次运行时,调用update_by_query会出现version_conflict_engine_exception错误。我猜测是因为120亿文档的大索引还在执行更新操作,这个猜测对吗?

内容的提问来源于stack exchange,提问作者VikR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:35:24