2016-05-11 130 views
1

我想知道是否可以根據代碼中的某些條件構建查詢。ElasticSearch根據條件構建查詢

self.search(query: { 
        bool: { 
         must: [ 
         { term: { country_id: country_id }}, 
         { term: { region_id: region_id }} => if region_id is not nil 
] 
        } 
        } 

在這個例子中,我想添加一行:

{ term: { region_id: region_id }} 

僅當REGION_ID不是零/出現在我的方法。

在SQL中,我可以使用多行和條件構建查詢。 我可以用ES做同樣的事嗎?

信息:在紅寶石在這裏工作

感謝

+0

我不認爲你可以像編程方式那樣做,但是需要在查詢本身中做到這一點。 –

+0

哦,我誤解了你的問題:-)。這只是在你的代碼... –

回答

1

你要創建一個查詢變量來構建查詢,並有條件地添加所需的元素(項)。試試看:

# Start with a base search definition 
query = { 
    query: { 
    bool: { 
     must: [ 
     { term: { country_id: country_id }} 
     ] 
    } 
    } 
} 

# Conditionally add search terms 
if region_id is not nil 
    query[:query][:bool][:must] << { term: { region_id: region_id }} 
end 

# Execute the search 
self.search(query) 
+0

完美的答案!不知道我可以使用的語法:'查詢[:查詢] [:布爾] [:必須]'謝謝! –