Home > Software design >  Elasticsearch get sibling documents for a document matching a query
Elasticsearch get sibling documents for a document matching a query

Time:10-21

I have parent and child documents in my Elasticsearch index related through a join: https://www.elastic.co/guide/en/elasticsearch/reference/6.3/parent-join.html.

I would like to be able to submit a query which matches on child documents and returns the siblings of the matching child documents.

My situation is i have students divided into groups, each student in my index is a separate child document and all students in the same group have the same parentId. The parent document contains no meaningful fields other than a groupId. My query is I want to get the list of all of the students who are in the group with student X with a single query. For example my query would look similar to:

{
   "query": {
      "match": {
         "studentName": "Bob"
      }
   }
}

And my response would list all the students who are in the same group as "Bob"

NOTE: I realize this problem could easily be solved by nesting the children who are in a group together into a single document, however, for my use case i cannot do this as i need to support a second query which is to be able to search for a student by name and return the results in sorted order based on relevancy. If i nest the student documents inside the same document, to my understanding, i can no longer achieve this second query.

Does anyone know if the search for siblings query is possible? Or more broadly does anyone know of any ES construct that would allow me to achieve both searching for students in the group with student X with a single query AND searching for student by name in a single query?

CodePudding user response:

Looks like that can be achieved by nesting has_child inside has_parent. Still, you cant sort by child doc's properties this query is going to be slow depending on your index size.

  • Related