Reputation: 557
I have an Elasticsearch index with documents that have the following fields:
Each of these fields may contain multiple user IDs.
I want to perform an aggregation that counts the total number of documents related to each user (either as author or contributor).
I can query each aggregation separately, but how do I combine them? Here's my query:
GET documents/_search
{
"aggs": {
"contributor": {
"terms": {
"field": "contributor"
}
},
"author": {
"terms": {
"field": "author"
}
}
}
}
Right now, I'm getting this result:
"aggregations": {
"author": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": 2,
"doc_count": 10
},
{
"key": 1,
"doc_count": 7
},
{
"key": 5,
"doc_count": 3
}
]
},
"contributor": {
"doc_count_error_upper_bound": 0,
"sum_other_doc_count": 0,
"buckets": [{
"key": 5,
"doc_count": 1
}]
}
}
But I'd like to have a single aggregation that returns the count of 4 documents for user 5.
Upvotes: 0
Views: 1593
Reputation: 1770
Well if you can update your mappings and add a field this should work. Please not it could be really slow (agg on string are slow and shouldnot be over used). Note if author = contributor in the same doc the agg will wont count 2 occurance (good news).
{
"mappings": {
"test": {
"properties": {
"contributor": {
"type": "keyword",
"copy_to": "author_and_contributor"
},
"author": {
"type": "keyword",
"copy_to": "author_and_contributor"
},
"author_and_contributor": {
"type": "string",
"fielddata": true
}
}
}
}
}
{
"size": 0,
"aggs": {
"author_contrib_agg": {
"terms": {
"field": "author_and_contributor"
}
}
}
}
Upvotes: 1