0
votes

So i have the below module in an ElasticSearch concern for my Model in rails.

This is working, but how do I make each of the bool query(must, must_not, filter) accept nil or empty parameters?

Say if I pass an empty query_string it would get all the documents. Then when I pass an empty size parameter it will return all sizes.

  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
1

1 Answers

1
votes

I solved a similar problem by constructing the query string on more of an as-needed basis, so I only included a clause if there was a search term for it. The query I sent to Elasticsearch only included the terms that were actually set by the user. For example:

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

(assuming the correct representation of the query, etc.)