从不同的文档查询不同的嵌套对象

时间:2019-01-17 03:22:09

标签: elasticsearch

假设我有两个文档的结构如下(假设还有更多相似的文档):

    doc1
    {
      "person_name": "foo",
      "food_likes": [
           { "name": "steak",
             "food_type": "meat",
             "extra_field": "field"
           },
           { "name": "chocolate cake",
             "food_type": "dairy",
              "extra_field": "field"
           }
       ]
   }
    doc2
    {
      "person_name": "bar",
      "food_likes": [
           { "name": "carrots",
             "food_type": "vegetable"
             "extra_field": "field"
           },
           { "name": "chocolate cake",
             "food_type": "dairy",
             "extra_field": "field"
           }
       ]
   }

我想进行查询,导致以下两个嵌套文档(忽略fieldsinner_hits等)

  hits: [{ "person_name": "foo",
      "food_likes": [ {
          "name" : "steak",
          "food_type": "meat"}
       ]
     },
     { "person_name": "bar",
      "food_likes": [ {
          "name" : "chocolate cake",
          "food_type": "dairy"}
       ]
     }]

其中每个文档都返回了一个嵌套文档(从文档1中,我选择了name="steak"嵌套对象,仅返回了namefood_type字段。文档中,我选择了name="chocolate cake"嵌套的对象,只返回了namefood_type字段。

我想到的查询是:

{
 "fields": ["person_name"],

  "query":{
     "bool": {
         "filter":[
            {"terms": {
                 "person_name": ["foo","bar"]
            }},
            {"nested": {
               "path":"food_likes",
               "inner_hits": {
                  "_source":[
                      "name",
                       "food_type"
                   ]
                },
                "query":{
                    "bool":{
                       "filter": [
                          {"terms":{
                              "food_likes.name":["steak", "chocolate cake"]
                           }}
                        ]
                     }
                 }

            }}
          ]

       }
   }
}

但是,这将执行["foo", "bar"]["steak", "chocolate cake"]的“笛卡尔积”。因此,name="chocolate cake"嵌套对象也将与文档1中的name="steak"对象一起返回。但是,我希望从steakfoo中提取chocolate cakebar获取。

是否可以在Elastic Search中对每个文档进行多个查询而不更改文档结构?我调查了has_parent,但似乎不适用于这里。

0 个答案:

没有答案