Search - Joining Queries Flashcards
What is?
In Elasticsearch, joining queries allow you to relate documents to one another, similar to join operations in relational databases. However, because Elasticsearch is a distributed, document-oriented database, it doesn’t support traditional joins between unrelated documents across indices.
Nested Query
Suppose you have documents for products with an array of reviews, each containing a reviewer and rating. The nested query lets you search for specific review criteria.
{
“query”: {
“nested”: {
“path”: “reviews”,
“query”: {
“bool”: {
“must”: [
{ “match”: { “reviews.reviewer”: “Alice” } },
{ “range”: { “reviews.rating”: { “gte”: 4 } } }
]
}
}
}
}
}
Finds products with a reviews object where the reviewer is “Alice” and the rating is at least 4.
has parent query
This requires a parent-child relationship, where documents are stored with a join field, associating child documents with their parents.
Assume you have article (parent) and comment (child) documents with a join field linking them.
{
“query”: {
“has_parent”: {
“parent_type”: “article”,
“query”: {
“match”: { “title”: “Elasticsearch” }
}
}
}
}
Finds comment documents where the parent article document has the title containing “Elasticsearch”.
Has Child Query
This example finds article documents with related comment children that have a rating of 5.
{
“query”: {
“has_child”: {
“type”: “comment”,
“query”: {
“match”: { “rating”: 5 }
}
}
}
}
Parent ID Query
Finding all child documents for a particular parent document.
{
“query”: {
“parent_id”: {
“type”: “comment”,
“id”: “article123”
}
}
}
Returns comment documents that have article123 as their parent.