能否在ElasticSearch查询语句中添加可被忽略的自定义调试字段?
在ElasticSearch查询中添加调试信息的简便方案
你遇到的问题是ES会严格校验查询DSL的字段,自定义的debug字段不属于bool查询或子查询的合法参数,因此会抛出解析错误。无需提前手动删除调试信息,以下两种方式更简便:
1. 使用官方支持的_name字段标记查询子句
ES允许给每个查询子句添加_name字段作为标识,该字段会被ES正常识别且不影响查询执行,甚至能在返回的匹配详情或explain结果中追踪对应子句的匹配情况,比自定义debug字段更实用。
修改后的查询示例:
{ "query": { "bool": { "_name": "base query", "must": [ { "_name": "date not in future", "range": { "date_add": { "lte": "2022-10-26 14:08:11" } } }, { "_name": "index X", "bool": { "must": [ { "_name": "match index X", "term": { "_index": "X" } } ] } } ], "must_not": [...], "should": [...] } } }
2. 利用ES的JSON注释功能(ES 7.10+)
如果仅需添加纯文本调试说明,ES 7.10及以上版本支持在查询DSL中添加JSON注释,格式为/* 调试内容 */或// 调试内容,注释会被ES解析时直接忽略:
{ "query": { "bool": { /* debug: base query */ "must": [ { // debug: date not in future "range": { "date_add": { "lte": "2022-10-26 14:08:11" } } }, { /* debug: index X */ "bool": { "must": [ { "term": { "_index": "X" } } ] } } ], "must_not": [...], "should": [...] } } }
这两种方式都无需提前删除调试内容,直接发送给ES即可正常解析执行。
内容的提问来源于stack exchange,提问作者Axi
相关产品推荐
相关产品推荐

