Elasticsearch 查询条件解析:使用should语句导致错误结果

本文将解析一个Elasticsearch查询条件,并解释为什么使用'should'语句会导致查询结果出现错误。

问题描述:

以下JSON查询条件旨在筛选满足特定条件的数据,但实际结果却包含了不应该被筛选出来的数据。

{
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "latestTs": {
                            "from": 1697644800000,
                            "to": null,
                            "include_lower": true,
                            "include_upper": true,
                            "boost": 1.0
                        }
                    }
                }
            ],
            "should": [
                {
                    "term": {
                        "smsSuccess": {
                            "value": false,
                            "boost": 1.0
                        }
                    }
                },
                {
                    "term": {
                        "emailSuccess": {
                            "value": false,
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "track_total_hits": 2147483647
}

问题分析:

该查询条件使用'should'语句,意味着只要满足其中任何一个条件即可,即使'smsSuccess'或'emailSuccess'为true,也可能被筛选出来。

解决方案:

为了确保仅返回'smsSuccess'和'emailSuccess'都为false的结果,需要将'should'语句改为'must'语句,表示必须同时满足所有条件。

{
    "query": {
        "bool": {
            "filter": [
                {
                    "range": {
                        "latestTs": {
                            "from": 1697644800000,
                            "to": null,
                            "include_lower": true,
                            "include_upper": true,
                            "boost": 1.0
                        }
                    }
                }
            ],
            "must": [
                {
                    "term": {
                        "smsSuccess": {
                            "value": false,
                            "boost": 1.0
                        }
                    }
                },
                {
                    "term": {
                        "emailSuccess": {
                            "value": false,
                            "boost": 1.0
                        }
                    }
                }
            ],
            "adjust_pure_negative": true,
            "boost": 1.0
        }
    },
    "track_total_hits": 2147483647
}

结论:

在Elasticsearch查询条件中,正确理解'should'和'must'语句的含义至关重要。使用'must'语句可以确保查询结果仅包含满足所有指定条件的文档。


原文地址: https://www.cveoy.top/t/topic/pmOF 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录