我想知道是否有可能根据我的代码中的某些条件来构建查询。
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做同样的事情吗?
信息:在这里工作的 ruby
谢谢
最佳答案
您将要创建一个查询变量来构建查询,并有条件地添加所需的元素(术语)。试试看:
# 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)
关于ruby-on-rails - ElasticSearch构建查询取决于条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37165976/