# Nested filter in aggregation query

**URL:** <https://discuss.elastic.co/t/nested-filter-in-aggregation-query/214196>\
**Category:** Elasticsearch\
**Created:** [January 8, 2020, 9:24am UTC](https://discuss.elastic.co/t/nested-filter-in-aggregation-query/214196 "2020-01-08T09:24:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ankur\_Agarwal2](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ankur_agarwal2/32/45618_2.png) [@Ankur\_Agarwal2](https://discuss.elastic.co/u/Ankur_Agarwal2)\
**Post date:** [January 8, 2020, 9:24am UTC](https://discuss.elastic.co/t/nested-filter-in-aggregation-query/214196/1 "2020-01-08T09:24:57Z")

</div>

Hi Team,

I have running following aggregation query with nested filter

GET /\_search  
{  
"aggs": {  
"NAME": {  
"nested": {  
"path": "crm.LeadStatusHistory"  
},  
"aggs": {  
"agg\_filter": {  
"filter": {  
"bool": {  
"must": [  
{  
"nested": {  
"path": "crm",  
"query": {  
"terms": {  
"crm.City.keyword": [  
"Rewa"  
]  
}  
}  
}  
},  
{  
"nested": {  
"path": "crm",  
"query": {  
"terms": {  
"crm.LeadID": [  
27961  
]  
}  
}  
}  
}  
]  
}  
},  
"aggs": {  
"agg\_terms":{  
"terms": {  
"field": "crm.LeadStatusHistory.StatusID",  
"size": 1000  
}  
}  
}  
}  
}  
}  
}  
}

-----\> i have following document  
{  
"\_index" : "crm",  
"\_type" : "\_doc",  
"\_id" : "4478",  
"\_score" : 1.0,  
"\_source" : {  
"crm" : [  
{  
"LeadStatusHistory" : [  
{  
"StatusID" : 3  
},  
{  
"StatusID" : 2  
},  
{  
"StatusID" : 1  
}  
],  
"LeadID" : 27961,  
"City" : "Rewa"  
},  
{  
"LeadStatusHistory" : [  
{  
"StatusID" : 1  
},  
{  
"StatusID" : 3  
},  
{  
"StatusID" : 2  
}  
],  
"LeadID" : 27959,  
"City" : "Rewa"  
}  
]  
}  
}]

However in response i am getting following result  
"aggregations" : {  
"NAME" : {  
"doc\_count" : 4332,  
"agg\_filter" : {  
"doc\_count" : 1,  
"agg\_terms" : {  
"doc\_count\_error\_upper\_bound" : 0,  
"sum\_other\_doc\_count" : 0,  
"buckets" : [  
{  
"key" : 1,  
"doc\_count" : 1  
}  
]  
}  
}  
}  
}

Query===\> As per source document, i have 3 nested 'crm.LeadStatusHistory' documents for crm.LeadID = 27961. However, results shows for agg\_filter equals to 1 instead of 3. Can you please let me know the reason for this case.

---

<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:** [February 5, 2020, 9:28am UTC](https://discuss.elastic.co/t/nested-filter-in-aggregation-query/214196/2 "2020-02-05T09:28:39Z")

</div>

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