如何在Elasticsearch中使用查询DSL查找最近/最接近的号码 [英] how to find the nearest / closest number using Query DSL in elasticsearch

查看:58
本文介绍了如何在Elasticsearch中使用查询DSL查找最近/最接近的号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种借助Elasticsearch查找最接近的价格/编号的可能性.问题是我没有范围.我要实现的是,结果按最近距离排序.根据示例搜索查询,我的索引包含3个具有以下价格(数字)的文档:45、27、32

i am looking for a possibility to find the nearest price / number with the help of elasticsearch. the problem is that i do not have a range. what i want to achieve is that the results are sorted by nearest distance. according to the example search query my index contains 3 documents with the following prices (numbers): 45, 27, 32

与我的搜索值29的给定数字之间的距离"为45-29 = 16 |27-29 = -2 |32-29 = 3,所以我希望搜索结果是按距离"进行评分的,该数字与给定的价格相距甚远.

the "distance" from my search value 29 for the given numbers are 45 - 29 = 16 | 27 - 29 = -2 | 32 - 29 = 3 so what i would expect is that the search results are scored by the "distance" the number is away from the given price.

搜索查询示例:

GET myawesomeindex/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "description": "this is the text i want to find"
          }
        },
        {
          "match": {
            "price": 29
          }
        }
      ]
    }
  }
}

我认为我的问题与以下类似问题有关:

i think my question is related to this similar question: 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"
    }
  }

并且您需要启用动态脚本.

您也可以这样做

  "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
            }
          }
        }
      ]
    }
  }

但这会改变得分本身.如果您想按距离(而不是其他)进行纯排序,那么我相信第一个选择是最好的.

But this will alter the score itself. If you want pure sorting by the distance (and nothing else) then I believe the first option is the best.

这篇关于如何在Elasticsearch中使用查询DSL查找最近/最接近的号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆