I have following index:
PUT /nested { "settings": { "number_of_shards": 1, "number_of_replicas": 0 }, "mappings": { "_doc": { "properties": { "name": {"type": "keyword"}, "my_price": {"type": "float"}, "offers": { "properties": { "type": {"type": "keyword"}, "shops": { "type": "nested", "properties": { "position": {"type": "integer"}, "price": {"type": "float"}, "name": {"type": "keyword"} } } } } } } } }
Lets fill it with some data:
POST /nested/_doc/1 { "name": "Product 1", "my_price": 200, "offers": { "type": "Type 1", "shops": [ { "positon": 1, "price": 100, "name": "Shop 1" }, { "positon": 2, "price": 200, "name": "Shop 2" }, { "positon": 3, "price": 300, "name": "Shop 3" } ] } } POST /nested/_doc/2 { "name": "Product 2", "my_price": 1000, "offers": { "type": "Type 1", "shops": [ { "positon": 1, "price": 1000, "name": "Shop 2" }, { "positon": 2, "price": 2000, "name": "Shop 1" }, { "positon": 3, "price": 3000, "name": "Shop 3" }, { "positon": 4, "price": 4000, "name": "Shop 4" } ] } }
Then I need to get:
- unique shop names + count of products for each shop (no problem with this aggregation)
- count of shops, which price is smaller than
my_price
POST /nested/_search { "size": 0, "aggs": { "shops": { "nested": { "path": "offers.shops" }, "aggs": { "shop_names": { "terms": { "field": "offers.shops.name", "size": 10 } }, "cheaper_than_me": { "filter": { "script": { "script": { "source": "doc['offers.shops.price'].value < doc['my_price'].value" } } } } } } } }
Response:
"aggregations" : { "shops" : { "doc_count" : 7, "shop_names" : { "doc_count_error_upper_bound" : 0, "sum_other_doc_count" : 0, "buckets" : [ { "key" : "Shop 1", "doc_count" : 2 }, { "key" : "Shop 2", "doc_count" : 2 }, { "key" : "Shop 3", "doc_count" : 2 }, { "key" : "Shop 4", "doc_count" : 1 } ] }, "cheaper_than_me" : { "doc_count" : 0 } } }
You can see, that cheaper_than_me.doc_count: 0
is not correct. There should be cheaper_than_me.doc_count: 1
The problem is, that doc['my_price'].value
is always 0.0
(dumped using Debug.explain()
). Any idea how to get this working? Is there any other method to access "parent" document values?