首页 > 解决方案 > 弹性搜索 | 如何搜索嵌套对象?

问题描述

我正在尝试创建一个搜索查询,该查询返回参与者同时为director和的所有文档owner。问题是这些数据分布在多个嵌套对象中。

请考虑以下两个文件:

{
      name: 'Facebook Inc.'
      participants: [
         {
           name: 'Mark Zuckerberg',
           roles: [
             {
               type: 'founder',
             },
             {
               type: 'owner',
             },
             {
               type: 'director',
             },

            ]
         }
      ] 
    },
    {
      name: 'Alphabet Inc.'
      participants: [
         {
           name: 'Larry Page',
           roles: [
             {
               type: 'founder',
             },
             {
               type: 'owner',
             }
            ]
         },
         {
           name: 'Sundar Pichai',
           roles: [
             {
               type: 'director',
             }
            ]
         },

      ] 
    }

索引方式如下:

{
  index: 'companies',
  body: {
    mappings: {
      company: {
        properties: {
           name: {type: 'text'},
           participants: {
             type: 'nested',
             properties: {
               name: {type: 'text'},
               roles: {
                 type: 'nested',
                 properties: {
                   type: {type: 'text'}
                 }
               }
             }
           }
        }
      }
    }
  }
}

问题:如何创建一个搜索查询来返回 aparticipantdirector的所有文档founder

预期的结果当然是 Facebook 的例子。

标签: elasticsearch

解决方案


这应该这样做:

{
  "query" : {
    "nested" : {
      "path" : "participants",
      "query" : {
        "bool" : {
          "must" : [
            {
              "nested" : {
                "path" : "participants.roles",
                "query" : {
                    "match" : { "participants.roles.type": "founder" }
                }
              }
            },
            {
              "nested" : {
                "path" : "participants.roles",
                "query" : {
                    "match" : { "participants.roles.type": "director" }
                }
              }
            }
            ]
        }
      }      
    }
  }
}

请注意,布尔查询的位置很重要。将它放在第一个嵌套查询中表明它必须是具有两个角色的参与者。


推荐阅读