elasticsearch 弹性检索:特定类别的搜索关键字结果

zfycwa2u  于 2022-12-29  发布在  ElasticSearch
关注(0)|答案(2)|浏览(148)

我正在尝试构建一个查询,尝试在其中搜索特定国家/地区的人名。如果输入JohnUSA,则只能找到人名为John的人的结果(通过属性:姓名)从美国(通过属性:国家),其他国家的结果不应出现在结果中。
我尝试过的:

"query": {
        "bool": {
            "should": [
                {
                    "multi_match": {
                        "query": "John",
                        "fields": ["username", "first_name", "last_name"],
                        "fuzziness": "AUTO",
                        "minimum_should_match": "50%"
                    }
                }
            ],
            "filter": [
                {
                    "match": {
                        "country": "USA"
                    }
                },
                {
                    "match": {
                        "is_citizen": true
                    }
                }
            ]
        }
    }

对于上面的查询,我看到的问题是,结果还显示了名字不是John但来自USA的人**。

Expectation : To filter results of given keyword specific to given country.
dnph8jn4

dnph8jn41#

您需要在名称查询中使用must子句,而不是使用should
下面的查询应该会给予你预期的结果。参考boolean query official doc以了解与示例的区别。

"query": {
        "bool": {
            "must": [ --> note `must` here
                {
                    "multi_match": {
                        "query": "John",
                        "fields": ["username", "first_name", "last_name"],
                        "fuzziness": "AUTO",
                        "minimum_should_match": "50%"
                    }
                }
            ],
            "filter": [
                {
                    "match": {
                        "country": "USA"
                    }
                },
                {
                    "match": {
                        "is_citizen": true
                    }
                }
            ]
        }
    }
ryevplcw

ryevplcw2#

您正在使用should子句,这就是它不起作用的原因。您可以使用must而不是should,它将解决您的问题。
您可以使用"type":"phrase_prefix"来匹配JoJohn
您可以按如下所示更改查询,它将正常工作:

"query": {
        "bool": {
            "must": [
                {
                    "multi_match": {
                        "query": "John",
                        "fields": ["username", "first_name", "last_name"],
                        "type":"phrase_prefix",
                        "minimum_should_match": "50%"
                    }
                }
            ],
            "filter": [
                {
                    "match": {
                        "country": "USA"
                    }
                },
                {
                    "match": {
                        "is_citizen": true
                    }
                }
            ]
        }
    }

相关问题