# How to get aggregation bucket keys in the term query block

**URL:** <https://discuss.elastic.co/t/how-to-get-aggregation-bucket-keys-in-the-term-query-block/245214>\
**Category:** Elasticsearch\
**Created:** [August 17, 2020, 10:14am UTC](https://discuss.elastic.co/t/how-to-get-aggregation-bucket-keys-in-the-term-query-block/245214 "2020-08-17T10:14:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Shrikanth\_M](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/shrikanth_m/32/47703_2.png) [@Shrikanth\_M](https://discuss.elastic.co/u/Shrikanth_M)\
**Post date:** [August 17, 2020, 10:14am UTC](https://discuss.elastic.co/t/how-to-get-aggregation-bucket-keys-in-the-term-query-block/245214/1 "2020-08-17T10:14:47Z")

</div>

How to get aggregation bucket keys in the term query block in the same query?

**Query**

```auto
{
   "size": 0,
   "query": {....},
   "aggs": {
      "customerId": {
		 "composite": {
			"sources": [
			   {
				  "customerId": {
					 "terms": {
						"field": "customerId"
					 }
				  }
			   }
			]
		 },
		 "aggs": {
			"items_count": {
			   "cardinality": {
				  "field": "itemId"
			   }
			},
			"item_count_bucket_sort": {
			   "bucket_sort": {
				  "size": 2,
				  "sort": [
					 {
						"items_count": {
						   "order": "desc"
						}
					 }
				  ]
			   }
			}
		 }
	  }
   }
}

```

**Output**

```auto
{
   "took": 71,
   "timed_out": false,
   "_shards": {
	  "total": 15,
	  "successful": 15,
	  "skipped": 0,
	  "failed": 0
   },
   "hits": {
	  "total": 173980,
	  "max_score": 0,
	  "hits": [x]
   },
   "aggregations": {
	  "customerId": {
		 "after_key": {
			"customerId": "CUST000000010"
		 },
		 "buckets": [
			{
			   "key": {
				  "customerId": "CUST000000007"
			   },
			   "doc_count": 12,
			   "items_count": {
				  "value": 4
			   }
			},
			{
			   "key": {
				  "customerId": "CUST000000008"
			   },
			   "doc_count": 10,
			   "items_count": {
				  "value": 4
			   }
			}
		 ]
	  }
   }
}

```

In the above output received customerId, need to set in the term query block.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [September 14, 2020, 10:14am UTC](https://discuss.elastic.co/t/how-to-get-aggregation-bucket-keys-in-the-term-query-block/245214/2 "2020-09-14T10:14:53Z")

</div>

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