Term Aggregation on sorted data

Hi,
i want to run some term aggregations on sorted data and i want these changes to be reflected inside the buckets.

Suppose i have an order_id field inside my document. I query over the index with size 0, while sort my data in order against order_id, and after it i'm using term aggregations. The query runs successfully. But the buckets contain data in complete random order.

Order inside aggregations i guess wont help because it will just sort the data already inside the bucket plus the i want order / sorting against order_id and the field in term aggregation is source_key

Here is the query i'm trying to write.

{
  "size": 0,
  "_source": false,
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "item_type_number": [
              9,
              10
            ]
          }
        }
      ],
      "must_not": {
        "has_child": {
          "type": "views",
          "query": {
            "bool": {
              "must": [
                {
                  "term": {
                    "user_id": 87
                  }
                }
              ]
            }
          }
        }
      }
    }
  },
  "sort": [
    {
      "order_id": {
        "order": "asc"
      }
    }
  ],
  "aggs": {
    "book": {
      "filter": {
        "bool": {
          "must": [
            {
              "terms": {
                "item_type_number": [
                  9
                ]
              }
            }
          ]
        }
      },
      "aggs": {
        "data": {
          "terms": {
            "field": "source_key",
            "size": 20
          }
        }
      }
    },
    "game": {
      "filter": {
        "bool": {
          "must": [
            {
              "terms": {
                "item_type_number": [
                  10
                ]
              }
            }
          ]
        }
      },
      "aggs": {
        "data": {
          "terms": {
            "field": "source_key",
            "size": 20
          }
        }
      }
    }
  }
}

You tried this:

what this aggregation does is it sorts the result within the buckets made. What i need is to sort data first and select some documents from the sorted list so in my case bucket sort won't help me.

I used collapse method to group the data and then sorted the results within this grouping.
Sample

,
  "collapse": {
    "field": "item_type_number",
    "inner_hits": {
      "name": "some_bucket_name_here",
      "size": 20,
      "sort": [
        {
          "order_id": {
            "order": "desc"
          }
        }
      ]
    }
  }

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.