Context
Assume you have a set of documents for which you have defined a nested mapping. Also assume that some documents have nested documents and some do not:
Document 1
{
"id":1,
"nested":[
{
"x":1
}
]
}
Document 2
{
"id":2,
"nested":[
{
"x":2
}
]
}
Document 3
{
"id":3
}
Problem
Is there a way to perform the equivalent of the following SQL query:
SELECT
r.id,
COUNT(*)
FROM
root r
LEFT JOIN
nested n
ON parent(n) = r
WHERE
n.x = 1 /* nested condition */
GROUP BY
r.id
Something that comes very close using ElasticSearch's query DSL is:
curl -XGET http://localhost:9200/nested/type/_search?pretty -d'
{
"fields":["id"],
"query":{
"nested":{
"query":{
"constant_score":{
"query":{
"term":{"x":1}
}
},
"boost":1.0
}
},
"path":"nested",
"score_mode":"total"
}
}
}'
However, since the semantics of nested queries and nested filters require a document to have at least one nested document, Document 3 would be filtered out here (i.e. "inner-join" semantics).
Is there a workaround / alternate approach to prevent documents from being excluded if they don't have a nested document?
Application
To note above is the condition on the nested documents. Although simple in this example, one can easily imagine situations where score based aggregations based on multiple dynamic conditions can not be precomputed in advance due to a combinatorial explosion.
The main value in the above query is that it includes results that have a score value of "0" and preserves a global document score sort and thus can not be computed using facets or the forthcoming Aggregation Module.