我正在寻找一种借助Elasticsearch查找最近价格/数量的可能性。问题是我没有范围。我要实现的是,结果按最近距离排序。根据示例搜索查询,我的索引包含3个具有以下价格(数字)的文档:45、27、32
给定数字与我的搜索值29的“距离”为45-29 = 16 | 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得分
你去了:
"sort": { "_script": { "type": "number", "script": "return doc['price'].value-distance", "params": { "distance": 29 }, "lang": "groovy", "order": "desc" } }
并且您需要启用动态脚本。
您也可以这样
"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自身。如果您想按距离(而不是其他)进行纯排序,那么我相信第一个选择是最好的。
score