Parent / Child Relationships in Elasticsearch - Returning the results I want

1.8k Views Asked by At

I'm working on setting up an Elasticsearch index and would like it to behave (return results) a certain way. I've got a parent / child relationship set up.

curl -XPUT 'http://127.0.0.1:9200/parent/' -d '
{
  "mappings": {
    "parent": {},
    "child": {
      "_parent": {
        "type": "parent" 
      }
    }
  }
} '

And I've populated it with some "parent" documents, and a bunch of "child" documents whose parent is correctly set.

When I search the content using with a normal search query I, of course, get back all documents that match. Parent and child documents but no tie between then. If I search the content using the has_child filter it correctly searches the child documents and returns to me the parent document that matches:

curl -XGET 'http://127.0.0.1:9200/parent/_search' -d '
{
  "query": {
    "has_child": {
      "type":         "child",
      "query": {
       "match": {
        "detail": "Stuff I Want To Match"
      }
    }
  }
} 
}'

The thing is, I want to search the children and get back the parent AND the children in a single document. Is there a way to accomplish this? Is the parent-child relationship the wrong one?

2

There are 2 best solutions below

2
On

This could be the most efficient way to do it, using "inner_hits" for parent/child relationship

Refer:https://github.com/elastic/elasticsearch/pull/8153

1
On

I want to do the same thing recently. And I figured out to print out the parent document and child documents into one elasticsearch result. But ideally it may be able to put parent and child into one json block.

Here is what I can do for now to get all the matching parent and child documents together.

curl -XGET 'http://127.0.0.1:9200/indexname/parent,child/_search' -d '
{
   "query": {
      "bool": {
         "should": [
            {
               "has_child": {
                  "type": "child",
                  "query": {
                     "match": {
                        "detail": "Stuff I Want To Match"
                     }
                  }
               }
            },
            {
               "match": {
                  "detail": "Stuff I Want To Match"
               }
            }
         ]
      }
   }
}'

Let's say you have 1 parent and 3 children match your condition, it will return 4 documents. 1 parent document and 3 children documents. I guess you probably want to have just 3 documents with some of the parent fields and child fields together.

That is what I want to solve next.

Hope this helps you.