Amine CHERIFI
Amine CHERIFI

Reputation: 1175

ElasticSearch: Getting parent's fields from a search on the child type

I have an index with two type (Parent/CHild relation) like this :

{
"myindex": {
    "mappings": {
        "b": {
            "_parent": {
                "type": "a"
            },
            "properties": {                 
                "b_propertie1": {
                    "type": "string",
                    "analyzer": "keyword_analyzer"
                },
                "b_propertie2": {
                    "type": "string",
                    "analyzer": "keyword_analyzer"
                }
            }
        },
        "a": {
            "properties": {
                "a_propertie1": {
                    "type": "string",
                    "analyzer": "keyword_analyzer"
                },
                "a_propertie2": {
                    "type": "string",
                    "analyzer": "keyword_analyzer"
                }
            }
        }
    }
 }
}

And i want to make a query that returns the fields of the parent and the child

POST /myindex/b/_search
{
   "fields" : ["b_propertie1", "b_propertie2", "a_propertie1", "a_propertie2"],
   "query": {
      "match": {
          "b_propertie1": "SOMETHING"
      }
    }
}

Is there any way to do it ? and how?

Thank you.

Upvotes: 0

Views: 322

Answers (1)

christinabo
christinabo

Reputation: 1130

ElasticSearch cannot merge fields from parent and child documents.

What you can do is to use the has_child query, which returns you parent documents that have child documents that match your query. By specifying the inner_hits parameters you also get as inner objects the child documents that matched the query.

"query": {
    "has_child": {
        "type": b, 
        "query": {
            "match": {
               "b_propertie1": "SOMETHING"
            }
        },
        "inner_hits": {
            '_source': {
                'includes': ['b_propertie1', 'b_propertie2']
            }
        }
    }
}

Then in your app, you can merge the fields from parent and child documents to get the result you want.

I hope it helps. :)

Upvotes: 1

Related Questions