Module: Elastics::SearchQuery

Includes:
QueryHelper
Defined in:
lib/elastics/search_query.rb

Overview

Helpers to build search query.

class Query
  include Elastics::SearchQuery

  # implement any of:
  #   query, phrase_query, query_filters, post_filter, aggregations

  def phrase_query
    {bool: {should: [
      {multi_match: {
        # ...
      }}
    ]}}
    # or just
    {math: {message: params[:query_string]}}
  end

  def query_filters
    [
      {term: {published: true}},
      terms_array_query(:tag, params[:tags], execution: :and),
      some_complex_filter,
    ]
  end

  def aggregations
    {
      tag: {terms: {
        field:      :tag,
        size:       10,
        shard_size: 10,
      }},
    }
  end
end

result = Model.search_elastics Query.new(params).as_json

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from QueryHelper

#normalize_filters, #normalize_query, #terms_array_query, #terms_query

Instance Attribute Details

#paramsObject (readonly)

Returns the value of attribute params.



43
44
45
# File 'lib/elastics/search_query.rb', line 43

def params
  @params
end

Instance Method Details

#aggregationsObject



81
82
# File 'lib/elastics/search_query.rb', line 81

def aggregations
end

#as_jsonObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/elastics/search_query.rb', line 49

def as_json
  page = params[:page] || 1
  per_page = params[:per_page] || 10
  result = {
    from:         (page - 1) * per_page,
    size:         per_page,
    fields:       [],
    query:        query,
    sort:         sort,
  }
  post_filter = self.post_filter
  result[:post_filter] = post_filter if post_filter
  aggregations = self.aggregations
  result[:aggregations] = aggregations if aggregations
  result
end

#initialize(params) ⇒ Object



45
46
47
# File 'lib/elastics/search_query.rb', line 45

def initialize(params)
  @params = params
end

#phrase_queryObject



71
72
# File 'lib/elastics/search_query.rb', line 71

def phrase_query
end

#post_filterObject



78
79
# File 'lib/elastics/search_query.rb', line 78

def post_filter
end

#queryObject

Builds query from phrase_query & query_filters.



67
68
69
# File 'lib/elastics/search_query.rb', line 67

def query
  normalize_query(phrase_query, query_filters.compact)
end

#query_filtersObject



74
75
76
# File 'lib/elastics/search_query.rb', line 74

def query_filters
  []
end

#sortObject

Takes ‘params` and returns it compatible with elastics. Wraps scalars into array, hashes are converted into arrays, array are passed as is.

{name: :asc, _score: :desc} => [{name: :asc}, {_score: :desc}]
:created_at => [:created_at]


90
91
92
93
94
95
96
97
# File 'lib/elastics/search_query.rb', line 90

def sort
  val = params[:sort]
  case val
  when Hash   then val.map { |x| Hash[[x]] }
  when Array  then val
  else val ? [val] : []
  end
end