首页 > 解决方案 > ElasticSearch:允许零参数的查询

问题描述

因此,我在 Rails 中的模型的 ElasticSearch 关注点中有以下模块。

这是可行的,但是如何使每个 bool 查询(must、must_not、filter)接受nil或空参数?

说如果我通过一个空的query_string它会得到所有的文件。然后,当我传递一个空size参数时,它将返回所有尺寸。

  module ClassMethods
    def home_page_search(query_string, size, start_date, end_date)
      search({
        query: {
          bool: {
            must: [
              {
                multi_match: {
                  query: query_string,
                  fields: [:brand, :name, :notes, :size_notes]
                }
              }
            ],
            must_not: [
              range: {
                unavailable_dates: { gte: start_date, lte: end_date }
              }
            ],
            filter: [
              { term: { size: size } }
            ]
          }
        }
      })
    end
  end

标签: ruby-on-railselasticsearch

解决方案


我通过更多地根据需要构建查询字符串解决了一个类似的问题,所以我只包含一个子句,如果有一个搜索词。我发送给 Elasticsearch 的查询仅包含用户实际设置的术语。例如:

if size.present?
  query[:query][:bool][:filter] = { term: { size: size } }
end

(假设查询的正确表示等)


推荐阅读