2016-02-24 137 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 
}