2016-02-24 173 views
2

我在彈性搜索中查詢時遇到問題。我正在搜索由state_id定義的特定數據集,然後想要返回所有沒有由以下標識符定義的城市之一的所有州。彈性搜索 - 或查詢不匹配

以下查詢將返回18個結果,僅顯示「city_id_1」,0個結果顯示「city_id_2」。儘管如此,我返回0結果(因爲「city_id_2」在每個狀態記錄上)。我想要做的仍然是返回18個結果,但是查詢兩個城市。

我覺得我的查詢應該是工作的,基本上做一個NOT(A或B)風格的查詢,相當於NOT A和非B,但基本上是0的結果似乎是壓倒一切的18

有沒有一種方法可以改變我的查詢來獲得我想要的結果,或者這是elasticsearch無法做到的事情?

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { "terms": { "state_id": ["4ca16f80-da79-11e5-9874-64006a4f57cb"]}} 
     ], 
     "must_not": [ 
     { 
      "nested": { 
      "path": "cities", 
      "query": { 
       "bool": { 
       "should": [ 
        {"term": { "cities.identifier": "city_id_1"}}, 
        {"term": { "cities.identifier": "city_id_2"}} 
       ] 
       } 
      } 
      } 
     } 
     ] 
    } 
    }, 
"size": 10 

} 

回答

0

如果你想NOT A AND NOT B行爲,你需要做出變化不大

{ 
"query": { 
"bool": { 
    "must": [ 
    { "terms": { "state_id": ["4ca16f80-da79-11e5-9874-64006a4f57cb"]}} 
    ], 
    "must_not": [ 
    { 
     "nested": { 
     "path": "cities", 
     "query": { 
      "bool": { 
      "must": [   ====> Use must instead of should 
       {"term": { "cities.identifier": "city_id_1"}}, 
       {"term": { "cities.identifier": "city_id_2"}} 
      ] 
      } 
     } 
     } 
    } 
    ] 
    } 
}, 
"size": 10 

} 

這將排除那些將同時擁有city_id_1和city_id_2記錄。

0

根據我的理解,您正在尋找我們的NOT A or NOT B種子句。請檢查下面的查詢,看看它是否符合您的要求

{ 
    "query": { 
    "bool": { 
     "must": [ 
     { "terms": { "state_id": ["4ca16f80-da79-11e5-9874-64006a4f57cb"]}} 
     ], 
     "should": [ 
     { 
      "nested": { 
      "path": "cities", 
      "query": { 
       "bool": { 
       "must_not": [ 
        {"term": { "cities.identifier": "city_id_1"}} 
        ] 
       } 
      } 
      } 
     }, 
     { 
      "nested": { 
      "path": "cities", 
      "query": { 
       "bool": { 
       "must_not": [ 
        {"term": { "cities.identifier": "city_id_2"}} 
        ] 
       } 
      } 
      } 
     } 
     ], 
     "minimum_number_should_match": 1 
    } 
    }, 
"size": 10 

} 
2

試試這個的尺寸。 Elasticsearch是愚蠢的。篩選器需要位於每個嵌套查詢中。

{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "query": { 
      "bool": { 
       "must_not": [ 
       { 
        "nested": { 
        "path": "cities", 
        "query": { 
         "term": { "cities.identifier": "city_id_1"} 
        } 
        } 
       } 
       ], 
       "filter":[ 
       { 
        "term":{ 
        "state_id":"4ca16f80-da79-11e5-9874-64006a4f57cb" 
        } 
       } 
       ] 
      } 
      } 
     }, 
     { 
      "query": { 
      "bool": { 
       "must_not": [ 
       { 
        "nested": { 
        "path": "cities", 
        "query": { 
         "term": { "cities.identifier": "city_id_2"} 
        } 
        } 
       } 
       ], 
       "filter":[ 
       { 
        "term":{ 
        "state_id":"4ca16f80-da79-11e5-9874-64006a4f57cb" 
        } 
       } 
       ] 
      } 
      } 
     } 
     ] 
    } 
    }, 
    "size": 10 
}