2017-05-11 56 views
0

我有一个索引,其中有三个字段type,它是一个整数,coordinates是一个地址点,title是一个字符串。我想查询title上的匹配项。然后我想有条件地过滤我的结果。如果它们落在15公里半径范围内,则应包括type 2的记录。那些不属于type 2的人应该只包括在7.5公里范围内。下面的查询并未达到此目的;我宁愿将它包含在内,以便对我的索引结构有所了解。该查询返回类型2且落在15公里内的匹配记录。我希望这个查询被扩展为包含不是类型2(即1)的匹配记录,但是只有它们落在7.5公里内。这可以在单个ES查询中实现吗?Elasticsearch中的条件过滤

伪我的过滤条件的逻辑:

if type == 2 
    filter 
     distance: 15 km 
else 
    filter 
     distance 7.5 km 

查询:

{ 
    "query": { 
    "filtered": { 
     "query": { 
     "match": { 
      "title": "my search terms" 
     } 
     }, 
     "filter": { 
     "and": [ 
      { 
      "geo_distance": { 
       "distance": "15km", 
       "coordinates": [ 
       -79.3931, 
       43.6709 
       ] 
      } 
      }, 
      { 
      "term": { 
       "type": "2" 
      } 
      } 
     ] 
     } 
    } 
    } 
} 

ES 2.3

回答

1

你可以达到你想要的东西是这样的:

{ 
    "query": { 
    "bool": { 
     "must": { 
     "match": { 
      "title": "my search terms" 
     } 
     }, 
     "should": [ 
     { 
      "bool": { 
      "must": [ 
       { 
       "geo_distance": { 
        "distance": "15km", 
        "coordinates": [ 
        -79.3931, 
        43.6709 
        ] 
       } 
       }, 
       { 
       "term": { 
        "type": "2" 
       } 
       } 
      ] 
      } 
     }, 
     { 
      "bool": { 
      "must": [ 
       { 
       "geo_distance": { 
        "distance": "7.5km", 
        "coordinates": [ 
        -79.3931, 
        43.6709 
        ] 
       } 
       } 
      ], 
      "must_not": { 
       "term": { 
       "type": "2" 
       } 
      } 
      } 
     } 
     ] 
    } 
    } 
} 
+0

这个工作谢谢。只需要在'constant_score'>'filter'下嵌套外部'bool' – Abd00s

+0

不需要使用ES 2.x,很高兴它解决了问题。 – Val