在ElasticSearch中按数字字段上的距离排序

编程入门 行业动态 更新时间:2024-10-14 10:43:07
本文介绍了在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中按数字字段上的距离排序

本文发布于:2023-10-18 15:01:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   距离   数字   ElasticSearch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!