2017-09-26 128 views
1

我試圖完成在ElasticSearch嵌套文檔中布爾值AND的結果。假設我有以下兩個文件。在ElasticSearch中匹配嵌套文檔中的多個屬性

{ 
    "id": 1, 
    "secondLevels": [ 
     { 
      "thirdLevels": [ 
       { 
        "isActive": true, 
        "user": "[email protected]" 
       } 
      ] 
     }, 
     { 
      "thirdLevels": [ 
       { 
        "isActive": false, 
        "user": "[email protected]" 
       } 
      ] 
     } 
    ] 
} 
{ 
    "id": 2, 
    "secondLevels": [ 
     { 
      "thirdLevels": [ 
       { 
        "isActive": true, 
        "user": "[email protected]" 
       } 
      ] 
     } 
    ] 
} 

在這種情況下,我想只匹配文件(在這種情況下,ID:2)有兩個isActive: trueuser: [email protected]一個嵌套的文件。

{ 
    "query": { 
     "bool": { 
      "must": [ 
       { 
        "nested": { 
         "path": "secondLevels.thirdLevels", 
         "query": { 
          "bool": { 
           "must": [ 
            { 
             "term": { 
              "secondLevels.thirdLevels.isActive": true 
             } 
            }, 
            { 
             "term": { 
              "secondLevels.thirdLevels.user": "[email protected]" 
             } 
            } 
           ] 
          } 
         } 
        } 
       } 
      ] 
     } 
    } 
} 

然而,似乎是發生的是,我的查詢變成了兩份文件,因爲文件頭有一個thirdLevelisActive: true和另一thirdLevel具有適當的用戶。

有什麼辦法可以在查詢/過濾時嚴格執行此操作,還是必須在腳本中執行此操作?

+0

您正在使用什麼版本的彈性?我創建了一個索引並在本地測試了您的查詢,並且我只返回id = 2的用戶。我要求的原因是,我相信「必須」分組應該是默認爲AND,除非您可能以某種方式默認爲OR – Miek

回答

2

使用嵌套對象和嵌套查詢,您已經完成了大部分工作。

所有你現在要做的就是添加inner hits標誌,還可以使用source filtering用於移動整個secondLevels文件的方式進行:

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { 
      "nested": { 
      "path": "secondLevels.thirdLevels", 
      "query": { 
       "bool": { 
       "must": [ 
        { 
        "term": { 
         "secondLevels.thirdLevels.isActive": true 
        } 
        }, 
        { 
        "term": { 
         "secondLevels.thirdLevels.user": "[email protected]" 
        } 
        } 
       ] 
       } 
      }, 
      "inner_hits": { 
       "size": 100 
      } 
      } 
     } 
     ] 
    } 
    } 
}