Sorry, the docs probably are a bit vague. When flattened into the root, they are flattened into a unique field defined by their full dot path. E.g. it'll generate a field on the root called foo.bar.baz: [1,2,3]
, whereas a second field would generate a field called foo.bar.not_baz: [10,20,30]
Here is a simple demo, which shows that include_in_root
collapses to the same thing. It uses a simple sum and a nested sum:
PUT nested_test
{
"mappings": {
"test": {
"properties": {
"foo": {
"type": "nested",
"include_in_root": true,
"properties": {
"numbers": {
"type": "integer"
},
"other_numbers": {
"type": "integer"
}
}
}
}
}
}
}
POST /nested_test/test/
{
"foo": [
{
"numbers": 1,
"other_numbers": 10
},
{
"numbers": 2,
"other_numbers": 20
}
]
}
GET /nested_test/test/_search
{
"size": 0,
"aggs": {
"root_sum": {
"sum": {
"field": "foo.numbers"
}
},
"root_sum_other": {
"sum": {
"field": "foo.other_numbers"
}
},
"nested_sum": {
"nested": {
"path": "foo"
},
"aggs": {
"sum": {
"sum": {
"field": "foo.numbers"
}
}
}
},
"nested_sum_other": {
"nested": {
"path": "foo"
},
"aggs": {
"sum": {
"sum": {
"field": "foo.other_numbers"
}
}
}
}
}
}
And the output (note that root_sum + nested_sum are equal to 3, while root_sum_other + nested_sum_other are equal to 30):
{
"aggregations": {
"root_sum": {
"value": 3
},
"nested_sum": {
"doc_count": 2,
"sum": {
"value": 3
}
},
"root_sum_other": {
"value": 30
},
"nested_sum_other": {
"doc_count": 2,
"sum": {
"value": 30
}
}
}
}
But I can see how this might not work, since you are storing key:value pairs in the nested docs. So all value
fields would be collapsed together.
Yeah, that's fair. It's possible you may be stuck with scripts, unless you can split tenants into their own index (to isolate the mappings).
Could you instead update counts at index-time, so that summing isn't needed? E.g. when updating a document, instead of appending a new nested object, you just update the sum?