1

我在一个项目中使用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

并且参数可能通过 nil,我怎样才能使搜索 dsl 有效?

4

2 回答 2

1

我宁愿建议您使用searchkick gem for rails,它使弹性搜索变得如此简单,并使您的搜索更智能,查询更简单。

于 2016-12-08T06:50:06.270 回答
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

此搜索将得到正确的结果。options[:key] 可能为 nil 会导致错误的结果,所以我要删除 dsl 哈希的 nil 键,然后将其传递给 search()

于 2016-12-08T05:09:49.387 回答