簡體   English   中英

彈性搜索 | 如何搜索嵌套對象?

[英]ElasticSearch | How to search for nested objects?

我正在嘗試創建一個搜索查詢,該查詢返回參與者既是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'}
                 }
               }
             }
           }
        }
      }
    }
  }
}

問題:如何創建一個搜索查詢來返回participant既是director又是founder所有文檔?

預期的結果當然是 Facebook 的例子。

這應該這樣做:

{
  "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" }
                }
              }
            }
            ]
        }
      }      
    }
  }
}

請注意 bool 查詢的位置很重要。 將它放在第一個嵌套查詢中表示它必須是具有兩個角色的參與者。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM