2016-01-22 279 views
4

我是Elasticsearch的新手,我試圖創建一個過濾器來檢索具有特定屬性的文檔。Elasticsearch嵌套對象過濾器

的屬性定義爲嵌套對象的映射,像這樣:

"attributes": { 
    "type": "nested", 
    "properties" : { 
     "id": { 
     "type": "integer" 
     }, 
     ... 
    } 
    } 
} 

我想要的形式執行復雜查詢:

(attribute.id == 1 OR attribute.id == 2) AND (attribute.id == 3 OR attribute.id == 4) 

據我所閱讀到目前爲止我已創建以下查詢以es:

{ 
    "query": { 
    "filtered": { 
    "query": { 
     "match_all": {} 
    }, 
    "filter": { 
     "nested": { 
      "path": "attributes", 
      "filter": { 
       "bool": { 
       "must": [ 
        { "bool" : { 
         "should" : [ 
         { "term": { "attributes.id": 1 }}, 
         { "term": { "attributes.id": 2 }} 
         ] 
        }}, 
        { "bool" : { 
         "should" : [ 
         { "term": { "attributes.id": 3 }}, 
         { "term": { "attributes.id": 4 }} 
         ] 
        }} 
       ] 
       } 
      } 
     } 
    } 
    } 
}, 
"sort": { 
    "date": { "order": "desc" } 
    } 
} 

但是,這不會返回任何重新sults。如果我刪除must塊中的兩個bools中的一個,它會正確過濾文檔。

存在同樣的問題(沒有結果),如果我更改查詢(用於測試目的)到:

"must": [ 
    { "term": { "attributes.id": 3 }}, 
    { "bool" : { 
    "should" : [ 
     { "term": { "attributes.id": 1 }}, 
     { "term": { "attributes.id": 2 }} 
    ] 
    }} 
] 

這在我的理解轉化爲attributes.id == 3 AND (attributes.id == 1 OR attributes.id == 2)

這是elasticsearch 2.x版本我做錯了什麼?

+0

也許每個'bool'子句可以在它自己的'nested'子句中?而不是將它們全部包裝在一起。 –

+0

@EvaldasBuinauskas我會盡力回覆你。 – mobius

+0

你可以發佈一個你期望被這個查詢返回的示例文檔嗎? – goalie7960

回答

3

爲了獲得您正在查找的結果,您需要執行兩個單獨的nested查詢,並將它們與bool查詢連接在一起。

下面是一個例子:由於與嵌套的文件和嵌套查詢一個微妙的差別

{ 
    "bool":{ 
    "must":[ 
     { 
     "nested":{ 
      "path":"attributes", 
      "filter":{ 
      "bool":{ 
       "should":[ 
       { "term": {"attributes.id": 1 }}, 
       { "term": {"attributes.id": 2 }} 
       ] 
      } 
      } 
     } 
     }, 
     { 
     "nested":{ 
      "path":"attributes", 
      "filter":{ 
      "bool":{ 
       "should":[ 
       { "term": {"attributes.id": 3 }}, 
       { "term": {"attributes.id": 4 }} 
       ] 
      } 
      } 
     } 
     } 
    ] 
    } 
} 

這樣做的原因是。有一看documentation on nested queries的一部分表示:

該查詢針對嵌套對象執行/文檔,就好像它們 被索引爲單獨的文檔(它們是,在內部),併產生 根父doc(或父嵌套映射)。

當做nested查詢,你實際上並沒有對根文檔進行查詢(儘管它感覺這種方式)。該查詢針對嵌套文檔進行操作,就好像它們是單獨的文檔一樣。

因此,當查詢針對具有 ID =一個嵌套文件(1或2)和ID =(3或4)你沒有結果。在您的數據中,每個嵌套文檔都只有這些id值中的一個。

+0

你是對的! (就像@EvaldasBuinauskas在上面的評論中指出的那樣)最讓我困惑的是,讓一個單人應該在一個必須布爾內工作的事實。 – mobius

+0

非常感謝。它非常清楚。很好的幫助。 –