弹性查询仅返回最大分数记录

时间:2019-05-09 11:11:43

标签: elasticsearch elastic-stack

我将传递一个应该查询的弹性值。它应该仅从结果中获取最大分数记录。

Records in my index : 
    GET testindex1/_search
    "hits" : [
              {
                "_index" : "testindex1",
                "_type" : "doc",
                "_id" : "2",
                "_score" : 1.0,
                "_source" : {
              "name" : "xyz",
              "description" : "better",
              "place" : "kerala"
            }
          },
          {
            "_index" : "testindex1",
            "_type" : "doc",
            "_id" : "3",
            "_score" : 1.0,
            "_source" : {
              "name" : "abc",
              "description" : "best",
              "place" : "andra"
            }
          },
          {
            "_index" : "testindex1",
            "_type" : "doc",
            "_id" : "1",
            "_score" : 1.0,
            "_source" : {
              "name" : "mno",
              "description" : "good",
              "place" : "tamil"
            }
          }
        ]

    Query passed:



GET testindex1/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "default_field": "name",
            "query": "xyz",
            "default_operator": "AND"
          }
        },
        {
          "query_string": {
            "default_field": "description",
            "query": "*",
            "default_operator": "AND"
          }
        },
        {
          "query_string": {
            "default_field": "place",
            "query": "*",
            "default_operator": "AND"
          }
        }
      ]
    }
  }
}


Results for the above query:

"hits" : {
    "total" : 3,
    "max_score" : 2.287682,
    "hits" : [
      {
        "_index" : "testindex1",
        "_type" : "doc",
        "_id" : "2",
        "_score" : 2.287682,
        "_source" : {
          "name" : "xyz",
          "description" : "better",
          "place" : "kerala"
        }
      },
      {
        "_index" : "testindex1",
        "_type" : "doc",
        "_id" : "3",
        "_score" : 2.0,
        "_source" : {
          "name" : "abc",
          "description" : "best",
          "place" : "andra"
        }
      },
      {
        "_index" : "testindex1",
        "_type" : "doc",
        "_id" : "1",
        "_score" : 2.0,
        "_source" : {
          "name" : "mno",
          "description" : "good",
          "place" : "tamil"
        }
      }
    ]
  }

对于上述查询,最大分数为2.287682,我只想显示具有最大分数的记录。在我的情况下,记录可能超过1条。我不能使用必须查询。我想从传递的查询中获取最佳结果

1 个答案:

答案 0 :(得分:0)

我不相信elasticsearch会在一个请求中提供类似的功能。 有两种选择。

  1. 如果结果数最多,则可以指定该数字(例如,即使有更多结果,我也希望得到最好的20个)。然后要求该size: 20,然后仅在应用程序级别过滤结果。 max_score可用,每个文档的分数也可用。
  2. 第二个方法是使用size: 1filter_path=hits.max_score进行请求,以获得最高分,然后再添加字段min_score https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-min-score.html进行第二个请求。这意味着对于每个请求,您实际上需要进行两个请求,但是您会获得所需的行为。