elasticsearch - Elasticsearch 查询在应该查询中查找匹配项的数量
问题描述
我正在寻求您的帮助来构建以下解决方案:
这是什么查询:如果五个字段(如街道、城市、姓氏、国家、大陆)中的任何一个字段(如街道、城市、姓氏、国家、大陆)中的任何一个,则查询该关键字是否存在,以便我想检查具有美国或英国的这些字段中的任何一个
我在寻求什么帮助。
获得 2 分:如果在这五个(“街道”、“城市”、“姓氏”、“国家”、“大陆”)字段中的任何一个中都找到了关键词“美国”、“英国”
得 1 分:如果在这五个(“街道”、“城市”、“姓氏”、“国家”、“大陆”)字段中的任何一个中找到“美国”、“英国”中的任何一个
得分 0:如果在这五个(“街道”、“城市”、“姓氏”、“国家”、“大陆”)字段中的任何一个字段中都没有找到这些关键词“美国”、“英国”
这样我就可以在前端结果中显示 0/2 或 1/2 或 2/2
现有查询:
GET main_index/_doc/_search
{
"query": {
"bool": {
"should": [
{
"multi_match": {
"fields": ["street","city","lastname","country","continent"],
"query": "united states",
"type": "phrase"
}
},
{
"multi_match": {
"fields": ["street","city","lastname","country","continent"],
"query": "united kingdom",
"type": "phrase"
}
}]
}
}
}
解决方案
有两种方法可以解决这个问题。
(注:我将下面的查询简化为对单个address
字段进行查询,但原理保持不变)
1.命名查询+应用逻辑
正如Val在评论中提到的,您可以使用命名查询(例如命名它们us-query
和uk-query
)来知道哪个项目与哪个查询匹配。
然后,您可以让您的应用程序代码解析matched_queries
每个结果的字段,以了解哪个查询匹配并在将结果返回到前端之前分配相关分数:
{
"query": {
"bool": {
"should": [
{
"multi_match": {
"fields": ["address"],
"query": "united states",
"type": "phrase",
"_name": "us-query"
}
},
{
"multi_match": {
"fields": ["address"],
"query": "united kingdom",
"type": "phrase",
"_name": "uk-query"
}
}]
}
}
}
2.功能评分
您可以使用类型的函数 scorescript_score
与filter
参数一起为每个查询分配正确的分数。我个人不喜欢这种解决方案,因为它使用过于复杂的查询来获得相当简单的结果,并在查询中引入了一些重复。
{
"query": {
"function_score": {
"query": { "match_all": {} },
"functions": [
{
"filter": {
"multi_match": {
"fields": ["address"],
"query": "united states",
"type": "phrase",
}
},
"script_score" : {
"script" : {
"source": "1"
}
}
},
{
"filter": {
"multi_match": {
"fields": ["address"],
"query": "united kingdom",
"type": "phrase",
}
},
"script_score" : {
"script" : {
"source": "1"
}
}
},
{
"filter": {
"bool": {
"must": [
{
"multi_match": {
"fields": ["address"],
"query": "united kingdom",
"type": "phrase",
}
},
{
"multi_match": {
"fields": ["address"],
"query": "united states",
"type": "phrase",
}
}
]
}
},
"script_score" : {
"script" : {
"source": "2"
}
}
}
]
}
}
}
推荐阅读
- r - CMD 检查工具和不一致的结果
- python - 为什么我会丢失部分命令行参数?PHP/shell_exec
- java - 应用程序从后台返回后处理片段的后按
- ios - CGAffineTransform 文档中可能出现的错误
- c# - C# Selenium - 超时:从渲染器接收消息超时:30.000(会话信息:chrome=88.0.4324.104)
- anylogic - Anylogic自定义代理未加载?
- azure - 电影py:从内存中的文本到语音导入音频
- excel - 使用 VBA 将多个列复制到单独的新工作簿中
- r - 将多个矩阵组合成一个数据帧
- azure-api-management - APIM - 响应数据屏蔽