Querying nested objects with in nested objects and aggregation on the same

Dear ES Gurus,

Have been facing difficulties in querying nested objects with in nested objects.

DOC sample as below:

{  
  "Customer":{  
    "Profile":{
      "id": "1234",	
      "name":{  
        "firstName":"Test",
        "lastName":"Test"
      },
      "Memberships":[  
        {  
          "memberId":"1",
          "memberShipType":"Customer",
		  "rank": 1
          "sources":[  
            {  
              "id":"WEB",
              "sourceType":"DERIVED"
            }
          ]
        },
        {  
          "memberId":"1",
          "memberShipType":"Customer",
		  "rank": 2
          "sources":[  
            {  
              "id":"store",
              "sourceType":"ORDER"
            }
          ]
        }
      ]
    }
  }
}

Need to query against sources nested object on field "sourceType" : "DERIVED" and pull only those documents do the aggregation on "memberId" under memberships nested object.

The requirement is to find memberid and id with sourceType "DERIVED" and count of memberId unique values.

Hope i am clear, Please let me know

If you want to filter documents that can be a part of your aggregation you should use filter aggregation.

For example, below we are filtering docs with "memberships.memberShipType" : "customer" to be a part of the agg by_memberid:

{
    "size" : 0,
    "aggs" : {
        "by_nested" : {
            "nested" : {
                "path" : "memberships"
            },
            "aggs" : {
                "by_filter" : {
                     "filter" : { "match": { "memberships.memberShipType" : "customer"}},
                        "aggs" : {
                            "by_memberid" : {
                                "terms" : {"field" : "memberships.memberId"}
                            }
                        }
                }
            }
        }
    }
}
1 Like

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