Elasticsearch日志搜索:字段取值校验查询结果异常排查
问题根因
你编写的Elasticsearch查询逻辑存在错误:
bool.must_not数组下的所有条件是同时满足的关系,原始查询实际含义为:返回Field1≠A 且 Field2≠B 且 Field3≠C的记录- 你测试的记录字段为
Field1=C、Field2=B、Field3=C,其中Field2取值等于B,不满足Field2≠B的条件,因此不会被返回,和校验预期不符
正确查询实现
你的需求是找出任意字段不符合允许取值的记录,也就是只要不符合 Field1=A 且 Field2=B 且 Field3=C 的记录都需要返回,对应两种实现方案:
写法1:直接排除所有完全符合规则的记录(推荐,逻辑最直观)
GET compteas_stat_index_1/_search { "query": { "bool": { "must_not": [ { "bool": { "must": [ {"match": {"Field1": "A"}}, {"match": {"Field2": "B"}}, {"match": {"Field3": "C"}} ] } } ] } } }
该写法直接过滤掉完全符合规则的记录,返回的结果就是所有至少有一个字段取值不符合要求的记录。如果对应字段是未分词的keyword类型,建议把match替换为term查询,匹配精度更高。
写法2:匹配任意一个字段不符合规则的记录
GET compteas_stat_index_1/_search { "query": { "bool": { "should": [ {"bool": {"must_not": {"match": {"Field1": "A"}}}}, {"bool": {"must_not": {"match": {"Field2": "B"}}}}, {"bool": {"must_not": {"match": {"Field3": "C"}}}} ], "minimum_should_match": 1 } } }
这里minimum_should_match: 1表示只要满足三个should条件中的任意一个,对应记录就会被返回,完全匹配校验需求。
内容的提问来源于stack exchange,提问作者sysley
相关产品推荐
相关产品推荐

