我正在寻找在弹性搜索的帮助下找到最近的价格/号码的可能性。问题是我没有范围。
我想要实现的是结果按最近距离排序。根据示例搜索查询,我的索引包含 3 个文档,其价格(数字)如下:45、27、32
对于给定数字,距我的搜索值 29 的“距离”是
45 - 29 = 16 | 45 - 29 = 16 27 - 29 = -2 | 27 - 29 = -2 32 - 29 = 3 所以我期望的是搜索结果是根据数字与给定价格的“距离”进行评分的。
搜索查询示例:
GET myawesomeindex/_search
{
"query": {
"bool": {
"should": [
{
"match": {
"description": "this is the text i want to find"
}
},
{
"match": {
"price": 29
}
}
]
}
}
}
我认为我的问题与这个类似的问题有关:Elasticsearch 根据数字与查询的接近程度进行评分 https://stackoverflow.com/questions/15880103/elasticsearch-scoring-based-on-how-close-a-number-is-to-a-query
就这样:
"sort": {
"_script": {
"type": "number",
"script": "return doc['price'].value-distance",
"params": {
"distance": 29
},
"lang": "groovy",
"order": "desc"
}
}
并且您需要启用动态脚本 https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html#enable-dynamic-scripting.
你也可以这样做
"query": {
"function_score": {
"query": {
"bool": {
"should": [
{
"match": {
"description": "this is the text i want to find"
}
},
{
"match": {
"price": 29
}
}
]
}
},
"functions": [
{
"exp": {
"price": {
"origin": "29",
"scale": "1",
"decay": 0.999
}
}
}
]
}
}
但这将改变score
本身。如果您想要纯粹按距离排序(而不是其他),那么我相信第一个选项是最好的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)