在ElasticSearch中按数字字段上的距离排序 [英] Sorting by distance on a numeric field in ElasticSearch
本文介绍了在ElasticSearch中按数字字段上的距离排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于一个项目,我需要选择在过滤器范围内并且最接近数值的文档。
For a project I need to select documents which are within filter bounds and a closest to a numeric value. This is about a price and I cannot seem to find if this is possible.
说我有2个文档:
{
"name": "Document1",
"price": 46.12,
"tags": ["tag1", "tag2"]
}
{
"name": "Document2",
"price": 82.29,
"tags": ["tag1", "tag3"]
}
是否可以获取价格最接近66.23的文档?
Is it possible to get the document with the price closest to 66.23?
推荐答案
答案(感谢keety)是启用动态脚本并添加如下排序方法:
The answer (thanks to keety) was to enable dynamic scripting and add a sorting method like this:
{
"query": {
"filtered" : {
"query":{
"match_all" : { }
},
"filter": {}
}
},
"sort" : {
"_script" : {
"script" : "cur = (factor - doc['age'].value); if (cur < 0) { cur = cur * -1 } else { cur = cur}",
"type" : "number",
"params" : {
"factor" : 45
},
"order" : "asc"
}
}
}
从最近到最远排序,就像一种魅力。谢谢!
This sorts from closest to farthest and works like a charm. Thanks!
这篇关于在ElasticSearch中按数字字段上的距离排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文