has_parent query

In the previous type of query, has_child, we wanted to get records of the parent_type query based on a query that we executed against the child type. The has_parent query is useful for exactly the opposite purpose, that is, when we want to get all child type of records based on a query executed against the parent_type. Let's learn about this through an example.

We want to get all the features of a specific product that has the product id = c0003. We can use a has_parent query as follows:

GET amazon_products_with_features/_search
{
"query": {
"has_parent": {
"parent_type": "product", 1
"query": { 2
"ids": {
"values": ["c0001"]
}
}
}
}
}

Please note the following points, marked with the numbers in the query:

  1. Under the has_parent query, we need to specify the parent_type against which the query needs to be executed to get the children (features).
  2. The query element can be any Elasticsearch query that will be run against the parent_type. Here we want features of a very specific product and we already know the Elasticsearch ID field (_id) of the product. This is why we use the ids query with just one value in the array: c0001.

The result is all the features of that product:

{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "amazon_products_with_features",
"_type" : "doc",
"_id" : "c0001_screen_size",
"_score" : 1.0,
"_routing" : "c0001",
"_source" : {
"product_or_feature" : {
"name" : "feature",
"parent" : "c0001"
},
"feature_key" : "screen_size",
"parent_id" : "c0001",
"feature_value" : "14 inches",
"feature" : "Screen Size"
}
},
{
"_index" : "amazon_products_with_features",
"_type" : "doc",
"_id" : "c0001_processor_series",
"_score" : 1.0,
"_routing" : "c0001",
"_source" : {
"product_or_feature" : {
"name" : "feature",
"parent" : "c0001"
},
"feature_key" : "processor_series",
"parent_id" : "c0001",
"feature_value" : "Core i5",
"feature" : "Processor Series"
}
},
{
"_index" : "amazon_products_with_features",
"_type" : "doc",
"_id" : "c0001_clock_speed",
"_score" : 1.0,
"_routing" : "c0001",
"_source" : {
"product_or_feature" : {
"name" : "feature",
"parent" : "c0001"
},
"feature_key" : "clock_speed",
"parent_id" : "c0001",
"feature_value" : "2.30 GHz",
"feature" : "Clock Speed"
}
}
]
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset