我正在寻找在 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 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"
}
}
并且您需要启用 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
}
}
}
]
}
}
但这会改变分数
本身。如果您只想按距离排序(而不是其他),那么我认为第一个选项是最好的。
关于elasticsearch - 如何在elasticsearch中使用查询DSL找到最近/最近的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37005785/