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

格式化含JSON的Elasticsearch查询字符串时出现KeyError错误求助

解决Python字符串format时的KeyError问题

你的代码报错是因为查询字符串里的大部分{}没有转义,str.format()会把所有未转义的大括号当成占位符解析,比如{"query"里的{会被识别为占位符开头,程序找不到对应的"query"键,所以抛出KeyError。

下面是两种解决办法:

方法一:转义非占位符的大括号

把所有不需要替换的{改成{{,}改成}},只保留要替换的{id}:

data = {'id': 20720}
query = '{{"query":{{"bool":{{"must":[{{"term":{{"status.keyword":"Running"}}}},{{"term":{{"id":{id}}}}}],"filter":[{{"term":{{"status.keyword":"Running"}}}}]}}}}}'
print(query.format(**data))

方法二:用字典构建查询再转JSON(更推荐)

这种方式不用处理字符串转义,字段多的时候更易维护:

import json

data = {'id': 20720}
query_dict = {
    "query": {
        "bool": {
            "must": [
                {"term": {"status.keyword": "Running"}},
                {"term": {"id": data['id']}}
            ],
            "filter": [
                {"term": {"status.keyword": "Running"}}
            ]
        }
    }
}
query = json.dumps(query_dict)
print(query)

两种方法都会输出你期望的结果:

{"query":{"bool":{"must":[{"term":{"status.keyword":"Running"}},{"term":{"id":20720}}],"filter":[{"term":{"status.keyword":"Running"}}]}}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:05:12