2015-06-19 32 views
3

我在嘗試嵌套聚合並對其應用過濾器。必須和應該運算符的嵌套搜索bool查詢

請看下面的例子:

汽車

  • 品牌
  • 功能

特點

下面是一些測試數據:

car_A: 
{ 
brand :"VW", 
name: "Golf", 
features: [ 
    {name: "color", value: "black"}, 
    {name: "power", value: "150"} 
] 
} 

car_B: 
{ 
brand :"VW", 
name: "Golf", 
features: [ 
    {name: "color", value: "blue"}, 
    {name: "power", value: "150"} 
] 
} 

car_C: 
{ 
brand :"VW", 
name: "Golf", 
features: [ 
    {name: "color", value: "white"}, 
    {name: "power", value: "150"} 
] 
} 

car_D: 
{ 
brand :"BMW", 
name: "X3", 
features: [ 
    {name: "color", value: "white"}, 
    {name: "power", value: "180"} 
] 
} 

car_E: 
{ 
brand :"BMW", 
name: "X5", 
features: [ 
    {name: "color", value: "blue"}, 
    {name: "power", value: "250"} 
] 
} 

car_F: 
{ 
brand :"BMW", 
name: "X3", 
features: [ 
    {name: "color", value: "blue"}, 
    {name: "power", value: "150"} 
] 
} 

和這裏的查詢:

"query": { 
"nested": { 
    "path": "features", 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "match": { 
      "features.color": "blue" 
      } 
     }, 
     { 
      "match": { 
      "features.color": "white" 
      } 
     } 
     ], 
     "must": [ 
     {"match": { 
      "features.power": 150 
     }} 
     ] 
    } 
    } 
} 
} 

查詢結果爲A,B,C, F

預期的結果應該是B,C,F(顏色=藍色OR顏色=白色)功率= 150

+0

我想你的結果是正確的,因爲'A'還包含'power = 150' – Yogesh

+0

問題就在那裏,因爲A中的features.color不是「藍色」而不是「白色」,所以OR在正常邏輯中會失敗。 should操作符不以這種方式表現。您認爲我應該將查詢更改爲AND和OR過濾器以實現預期結果嗎? (在生產中查詢也有一個聚合) – Zirc75

回答

2

嘗試此查詢:

"query": { 
"nested": { 
    "path": "features", 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "match": { 
      "features.color": "blue" 
      } 
     }, 
     { 
      "match": { 
      "features.color": "white" 
      } 
     } 
     ], 
     "must": [ 
     {"match": { 
      "features.power": 150 
     }} 
     ] 
    } 
    } 
} 
} 

含義,字段,你在查詢中使用時,應該以path的名稱作爲前綴:features.color,features.power

編輯

試試這個查詢(我錯過了重要的位置 - 你需要兩個must S,一個是boolshould S):

{ 
    "query": { 
    "nested": { 
     "path": "features", 
     "query": { 
     "bool": { 
      "must": [ 
      { 
       "match": { 
       "features.power": 150 
       } 
      }, 
      { 
       "bool": { 
       "should": [ 
        { 
        "match": { 
         "features.color": "blue" 
        } 
        }, 
        { 
        "match": { 
         "features.color": "white" 
        } 
        } 
       ] 
       } 
      } 
      ] 
     } 
     } 
    } 
    } 
} 
+0

嗨Stefan,你是對的,在我的例子中缺少路徑名。即使我指定(我必須)路徑前綴,問題仍然存在。 – Zirc75

+0

你說得對,問題在別的地方。我更新了我的答案。 –