当前位置: 动力学知识库 > 问答 > 编程问答 >

elasticsearch - Using inner hits to query data from parent-child relationship

问题描述:

I have data modelled using parent child relationship. I want to be able to fetch a particular child from a parent using inner hits- atleast that is what is my understanding from the definition of inner hits.

My mapping is :

{

"mappings": {

"parent_type": {

"properties": {

"num_prop": {

"type": "integer"

},

"str_prop": {

"type": "string"

}

}

},

"child_type": {

"_parent": {

"type": "parent_type"

},

"properties": {

"child_num": {

"type": "integer"

},

"child_str": {

"type": "string"

}

}

}

}

}

My data is:

{"index":{"_type":"parent_type","_id":1}}

{"num_prop":1,"str_prop":"hello"}

{"index":{"_type":"child_type","_id":1,"_parent":1}}

{"child_num":11,"child_str":"foo"}

{"index":{"_type":"child_type","_id":2,"_parent":1}}

{"child_num":12,"child_str":"bar"}

{"index":{"_type":"parent_type","_id":2}}

{"num_prop":2,"str_prop":"goodbye"}

{"index":{"_type":"child_type","_id":3,"_parent":2}}

{"child_num":21,"child_str":"baz"}

{"index":{"_type":"child_type","_id":4,"_parent":2}}

{"child_num":13,"child_str":"foo"}

As can be seen above, parent with id 1 has two children "foo" and "bar", and parent 2 also has a child "foo". Now I want to fecth foo and its parent 1 - which I am trying to do using inner hits.

{

"query": {

"has_child": {

"type": "child_type",

"query": {

"match": { "child_str": "foo"}

} }

},

"inner_hits": {

"parent_type" : {

"type" : {

"parent_type" : {

"query" : {

"match" : {"str_prop" : "hello"}

}

}

}

}

}

}

However, this does not work. Can someone please let me know what is wrong here?

Thanks and regards,

Priya

网友答案:

The answer is :

{
 "query": {
    "filtered": {
      "query": {


            "match": { "str_prop":   "hello"}


      },
      "filter":{
        "has_child": {
          "type": "child_type",
          "query" : {
            "filtered": {
              "query": { "match_all": {}},
              "filter" : {
                "and": [
                  {"match": {"child_str": "foo"}}
                ]
              }
            }
          },

          "inner_hits" : {}
        }
      }
    }
  }

}
分享给朋友:
您可能感兴趣的文章:
随机阅读: