1

I am trying to solve an issue where I have to get distinct result in the search.

{
        "name" : "ABC",
        "favorite_cars" : [ "ferrari","toyota" ]
      }, {
        "name" : "ABC",
        "favorite_cars" : [ "ferrari","toyota" ]
      }, {
        "name" : "GEORGE",
        "favorite_cars" : [ "honda","Hyundae" ]
      }

When I perform a term query on favourite cars "ferrari". I get two results whose name is ABC. I simply want that the result returned should be one in this case. So my requirement will be if I can apply a distinct on name field to receive one 1 result.

Thanks

2
  • As far as I know , you can't do this. The most you can do is to count them using terms aggregation. In my case , what I do is to remove them after using a Java set. If you find a way , let me know. Commented Dec 26, 2016 at 22:07
  • 1
    @Yeikel the solution provided by Val works for me. Is it helpful to you. Commented Dec 27, 2016 at 12:18

1 Answer 1

1

One way to achieve what you want is to use a terms aggregation on the name field and then a top_hits sub-aggregation with size 1, like this:

{
  "size": 0,
  "query": {
    "term": {
      "favorite_cars": "ferrari"
    }
  },
  "aggs": {
    "names": {
      "terms": {
        "field": "name"
      },
      "aggs": {
        "single_result": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}

That way, you'll get a single term ABC and then nested into it a single matching document

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Val that really helped.
@Val Do you know how "expensive" this aggregations are?
This one is not expensive at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.