# Parent-Child and cardinality aggregation

**URL:** <https://discuss.elastic.co/t/parent-child-and-cardinality-aggregation/90278>\
**Category:** Elasticsearch\
**Created:** [June 21, 2017, 11:56am UTC](https://discuss.elastic.co/t/parent-child-and-cardinality-aggregation/90278 "2017-06-21T11:56:56Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![martingrayson](https://avatars.discourse-cdn.com/v4/letter/m/6a8cbe/32.png) [@martingrayson](https://discuss.elastic.co/u/martingrayson)\
**Post date:** [June 21, 2017, 11:56am UTC](https://discuss.elastic.co/t/parent-child-and-cardinality-aggregation/90278/1 "2017-06-21T11:56:56Z")

</div>

I have a parent child relationship setup:

Customer (Parent) -\> Order Line (Child)

I'm trying to count the number of parents (customers) that have children matching two sets of criteria. i.e.  
I want the number of customers that have purchased **both** a Foo and a Bar.

At the moment, I can only get vaguely close to this by a complex series of bucketing, just using the child type.

```
GET customer_orderlines/orderline/_search
{
  "size": 0,
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "prod_key": "foo"
          }
        },
        {
          "match": {
            "prod_key": "bar"
          }
        }
      ]
    }
  },
  "aggs": {
    "customers": {
      "terms": {
        "field": "customer_key"
      },
      "aggs": {
        "matching_products": {
          "cardinality": {
            "field": "prod_key"
          }
        },
        "sales_bucket_filter": {
          "bucket_selector": {
            "buckets_path": {
              "matchingProducts": "matching_products"
            },
            "script": "params.matchingProducts > 1"
          }
        }
      }
    }
  }
}

```

Whats the correct way of doing this? Basically im trying to emulate the following sort of SQL

```
SELECT Count(DISTINCT customer_key) 
FROM (SELECT customer_key, 
               Count(DISTINCT product) AS prd_count 
        FROM orders 
        WHERE orders.product IN ( 'foo', 'bar' )) 
WHERE prd_count > 1
```

---

<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:** [July 19, 2017, 11:57am UTC](https://discuss.elastic.co/t/parent-child-and-cardinality-aggregation/90278/2 "2017-07-19T11:57:16Z")

</div>

Closed on July 19, 2017, 11:57am UTC

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