1

I would like to order the buckets from a terms aggregation based on a property possessed by the first element in a top hits aggregation.

My best effort query looks like this (with syntax errors):

{
    "aggregations": {
        "toBeOrdered": {
            "terms": {
                "field": "parent_uuid",
                "size": 1000000,
                "order": {
                    "topAnswer._source.id": "asc"
                }
            },
            "aggregations": {
                "topAnswer": {
                    "top_hits": {
                        "size": 1
                    }
                }
            }
        }
    }
}

Does anyone know how to accomplish this?

Example:

{
  "a":1,
  "b":2,
  "id":4
}
{
  "a":1,
  "b":3,
  "id":1
}
{
  "a":2,
  "b":4,
  "id":3
}

Grouping by "a" and ordering the buckets by "id" (desc) and sorting the top hits on "b" (desc) would give:

{2:{
  "a":2,
  "b":4,
  "id":3
},1:{
  "a":1,
  "b":3,
  "id":1
}}
Val
  • 207,596
  • 13
  • 358
  • 360
Bomaz
  • 1,871
  • 1
  • 17
  • 22

1 Answers1

1

You can do it with the following query. The idea is to show for each parent_uuid bucket the first top hit with the minimum id value and to sort the parent_uuid buckets according the smallest id value as well using a min sub-aggregation.

{
  "aggregations": {
    "toBeOrdered": {
      "terms": {
        "field": "parent_uuid",
        "size": 1000000,
        "order": {
          "topSort": "desc"
        }
      },
      "aggregations": {
        "topAnswer": {
          "top_hits": {
            "size": 1,
            "sort": {
              "b": "desc"
            }
          }
        },
        "topSort": {
          "max": {
            "field": "id"
          }
        }
      }
    }
  }
}

Try it out and report if this works out for you.

Val
  • 207,596
  • 13
  • 358
  • 360
  • My top_hits however have a different sorting order and I would like to order by the id as sorted by the top_hits. – Bomaz Oct 26 '15 at 12:12
  • What I understood from your question is that you would like `toBeOrdered` to be ordered by the `id` property of the first hit in your `top_hits` sub-aggregation. If not, can you show with some sample documents, how you would like the results to look like? – Val Oct 26 '15 at 12:16
  • Ok, I might have misunderstood your answer, please correct me if I'm wrong. My top_hits however aren't ordered by id, they have a different ordering. Also, updated main post with an example in an attempt to clarify – Bomaz Oct 26 '15 at 14:02
  • Thanks for the examples, they helped. I've updated my answer accordingly. – Val Oct 26 '15 at 14:07
  • Either I am missing something or wouldn't this sort on the max id in the bucket rather than the max id returned by the top_hits aggregation? – Bomaz Oct 26 '15 at 14:13