Search code examples
javajakarta-eeelasticsearchlucenequerydsl

Elastic search query based on score in the response


Can we query the ES to return only one result which is having highest score in the response, when there are multiple records matching the query?.

Let me know, if there is any sample query. thanks.

Sample response/document:- I use like search. As of now my service returns below records.

record1 - product1, value1, score=1.5 
record2 - product1, value2, score=1.4
record3 - product2, value1, score=1.7
record4 - product2, value2, score=0.8
record5 - product3, value1, score=1.2

I want the result with only below records, which will filter product, based on the score. Only one record per product.

record1 - product1, value1, score=1.5
record3 - product2, value1, score=1.7
record5 - product3, value1, score=1.2

Further details:- Created an custom Analyser:-

"analysis": {

    "filter": {
        "autocomplete_filter": {
            "type": "edge_ngram",
            "min_gram": "1",
            "max_gram": "20"
        }
    },
    "analyzer": {
        "autocomplete": {
            "filter": [
                "autocomplete_filter"
            ],
            "type": "custom",
            "tokenizer": "keyword"
        }
    }

}

Mapping:-

"PRODUCT_ID": {

    "analyzer": "autocomplete",
    "type": "string"

}

Query:-

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "PRODUCT_ID": "CON-HSH-AS"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "aggs": {}
}

Solution

  • You can check out top-hits aggregation. Maybe it'll be of help for your use case :)