我正在使用elasticsearch-rails作为项目,有一个联合搜索功能,所有列都在一个表中。我只是编写了一个自定义搜索功能,并且搜索dsl不起作用,不能有任何结果。
def self.combine_search_filter(remark=nil, sim_card_supplier_id=nil, work_mode=nil, operator_status=nil, platform_management_status=nil, online_status=nil, sim_card_set_id=nil, iccid_from=nil, iccid_to=nil, actived_at_from=nil, actived_at_to=nil, check_in_at_from=nil, check_in_at_to=nil, device_mac_from=nil, device_mac_to=nil)
response = __elasticsearch__.search(
"size": 1000,
"query": {
"filtered": {
"filter": {
"bool": {
"filter": [
{ "term": { "sim_card_supplier_id": sim_card_supplier_id } },
{ "term": { "work_mode": work_mode } },
{ "term": { "operator_status": operator_status } },
{ "term": { "platform_management_status": platform_management_status } },
{ "term": { "online_status": online_status } },
{ "term": { "sim_card_set_id": sim_card_supplier_id } }
{ "range": { "iccid": { "from": iccid_from, "to": iccid_to }}},
{ "range": { "check_in_at": { "from": check_in_at_from, "to": check_in_at_to }}},
{ "range": { "actived_at": { "from": actived_at_from, "to": actived_at_to }}},
{ "range": { "device_mac": { "from": device_mac_from, "to": device_mac_to }}}
]
}
}
}
}
)
end
并且params可能传递为nil,我怎么能这样做才能使搜索dsl有效?
答案 0 :(得分:1)
我建议您使用searchkick gem for rails,这样可以使弹性搜索变得简单,并使您的搜索更加智能,查询更简单。
答案 1 :(得分:0)
我的不好,我只想弄明白,ruby关键字功能应该是这样的:
def self.combine_search_filter(options = {})
response = __elasticsearch__.search(
"size": 1000,
"query": {
"filtered": {
"filter": {
"bool": {
"filter": [
{ "term": { "sim_card_supplier_id": 104 } },
{ "term": { "work_mode": options[:work_mode] } },
{ "term": { "operator_status": options[:operator_status] } },
{ "term": { "platform_management_status": options[:platform_management_status] } },
{ "term": { "online_status": options[:online_status] } },
{ "term": { "sim_card_set_id": 76 } },
{ "range": { "iccid": { "from": options[:iccid_from], "to": options[:iccid_to] }}},
{ "range": { "check_in_at": { "from": options[:check_in_at_from], "to": options[:check_in_at_to] }}},
{ "range": { "actived_at": { "from": options[:actived_at_from], "to": options[:actived_at_to] }}},
{ "range": { "device_mac": { "from": options[:device_mac_from], "to": options[:device_mac_to] }}}
]
}
}
}
}
)
end
此搜索将获得正确的结果。选项[:key]可能为nil会导致错误的结果,所以我要删除dsl哈希的nil键,然后将其传递给search()