2017-05-11 57 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