Class: NaranyaEcm::Search::Query

Inherits:
Hash
  • Object
show all
Defined in:
lib/naranya_ecm/search/query.rb

Class Method Summary collapse

Class Method Details

.build_searchkick_like(term, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/naranya_ecm/search/query.rb', line 5

def build_searchkick_like(term, options = {})
  if term.is_a?(Hash)
    options = term
    term = nil
  else
    term = term.to_s
  end

  fields =
    if options[:fields]
      if options[:autocomplete]
        options[:fields].map{|f| "#{f}.autocomplete" }
      else
        options[:fields].map do |value|
          k, v = value.is_a?(Hash) ? value.to_a.first : [value, :word]
          "#{k}.#{v == :word ? "analyzed" : v}"
        end
      end
    else
      ["_all"]
    end

  operator = options[:partial] ? "or" : "and"

  # model and eagar loading
  load = options[:load].nil? ? true : options[:load]
  load = (options[:include] ? {include: options[:include]} : true) if load

  # pagination
  page = [options[:page].to_i, 1].max
  per_page = (options[:limit] || options[:per_page] || 10).to_i
  offset = options[:offset] || (page - 1) * per_page

  all = term == "*"

  if options[:query]
    payload = options[:query]
  elsif options[:similar]
    payload = {
      more_like_this: {
        fields: fields,
        like_text: term,
        min_doc_freq: 1,
        min_term_freq: 1,
        analyzer: "searchkick_search2"
      }
    }
  elsif all
    payload = {
      match_all: {}
    }
  else
    if options[:autocomplete]
      payload = {
        multi_match: {
          fields: fields,
          query: term,
          analyzer: "searchkick_autocomplete_search"
        }
      }
    else
      queries = []
      fields.each do |field|
        if field == "_all" or field.end_with?(".analyzed")
          shared_options = {
            fields: [field],
            query: term,
            use_dis_max: false,
            operator: operator,
            cutoff_frequency: 0.001
          }
          queries.concat [
            {multi_match: shared_options.merge(boost: 10, analyzer: "searchkick_search")},
            {multi_match: shared_options.merge(boost: 10, analyzer: "searchkick_search2")}
          ]
          if options[:misspellings] != false
            distance = (options[:misspellings].is_a?(Hash) && options[:misspellings][:distance]) || 1
            queries.concat [
              {multi_match: shared_options.merge(fuzziness: distance, max_expansions: 3, analyzer: "searchkick_search")},
              {multi_match: shared_options.merge(fuzziness: distance, max_expansions: 3, analyzer: "searchkick_search2")}
            ]
          end
        else
          queries << {
            multi_match: {
              fields: [field],
              query: term,
              analyzer: "searchkick_autocomplete_search"
            }
          }
        end
      end

      payload = {
        dis_max: {
          queries: queries
        }
      }
    end

  end

  custom_filters = []

  if options[:boost]
    custom_filters << {
      filter: {
        exists: {
          field: options[:boost]
        }
      },
      script: "log(doc['#{options[:boost]}'].value + 2.718281828)"
    }
  end

  if custom_filters.any?
    payload = {
      custom_filters_score: {
        query: payload,
        filters: custom_filters,
        score_mode: "total"
      }
    }
  end

  payload = {
    query: payload,
    size: per_page,
    from: offset
  }
  payload[:explain] = options[:explain] if options[:explain]

  # order
  if options[:order]
    order = options[:order].is_a?(Enumerable) ? options[:order] : {options[:order] => :asc}
    payload[:sort] = Hash[ order.map{|k, v| [k.to_s == "id" ? :_id : k, v] } ]
  end

  term_filters =
    proc do |field, value|
      if value.is_a?(Array) # in query
        if value.any?
          {or: value.map{|v| term_filters.call(field, v) }}
        else
          {terms: {field => value}} # match nothing
        end
      elsif value.nil?
        {missing: {"field" => field, existence: true, null_value: true}}
      else
        {term: {field => value}}
      end
    end

  # where
  where_filters =
    proc do |where|
      filters = []
      (where || {}).each do |field, value|
        field = :_id if field.to_s == "id"

        if field == :or
          value.each do |or_clause|
            filters << {or: or_clause.map{|or_statement| {and: where_filters.call(or_statement)} }}
          end
        else
          # expand ranges
          if value.is_a?(Range)
            value = {gte: value.first, (value.exclude_end? ? :lt : :lte) => value.last}
          end

          if value.is_a?(Hash)
            if value[:near]
              filters << {
                geo_distance: {
                  field => value.delete(:near).map(&:to_f).reverse,
                  distance: value.delete(:within) || "50mi"
                }
              }
            end

            if value[:top_left]
              filters << {
                geo_bounding_box: {
                  field => {
                    top_left: value.delete(:top_left).map(&:to_f).reverse,
                    bottom_right: value.delete(:bottom_right).map(&:to_f).reverse
                  }
                }
              }
            end

            value.each do |op, op_value|
              if op == :not # not equal
                filters << {not: term_filters.call(field, op_value)}
              elsif op == :all
                filters << {terms: {field => op_value, execution: "and"}}
              else
                range_query =
                  case op
                  when :gt
                    {from: op_value, include_lower: false}
                  when :gte
                    {from: op_value, include_lower: true}
                  when :lt
                    {to: op_value, include_upper: false}
                  when :lte
                    {to: op_value, include_upper: true}
                  else
                    raise "Unknown where operator"
                  end
                filters << {range: {field => range_query}}
              end
            end
          else
            filters << term_filters.call(field, value)
          end
        end
      end
      filters
    end

  # filters
  filters = where_filters.call(options[:where])
  if filters.any?
    payload[:filter] = {
      and: filters
    }
  end

  # facets
  facet_limits = {}
  if options[:facets]
    facets = options[:facets] || {}
    if facets.is_a?(Array) # convert to more advanced syntax
      facets = Hash[ facets.map{|f| [f, {}] } ]
    end

    payload[:facets] = {}
    facets.each do |field, facet_options|
      # ask for extra facets due to
      # https://github.com/elasticsearch/elasticsearch/issues/1305

      if facet_options[:ranges]
        payload[:facets][field] = {
          range: {
            field.to_sym => facet_options[:ranges]
          }
        }
      else
        payload[:facets][field] = {
          terms: {
            field: field,
            size: facet_options[:limit] ? facet_options[:limit] + 150 : 100000
          }
        }
      end

      facet_limits[field] = facet_options[:limit] if facet_options[:limit]

      # offset is not possible
      # http://elasticsearch-users.115913.n3.nabble.com/Is-pagination-possible-in-termsStatsFacet-td3422943.html

      facet_filters = where_filters.call(facet_options[:where])
      if facet_filters.any?
        payload[:facets][field][:facet_filter] = {
          and: {
            filters: facet_filters
          }
        }
      end
    end
  end

  # highlight
  if options[:highlight]
    payload[:highlight] = {
      fields: Hash[ fields.map{|f| [f, {}] } ]
    }
    if options[:highlight].is_a?(Hash) and tag = options[:highlight][:tag]
      payload[:highlight][:pre_tags] = [tag]
      payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A</, "</")]
    end
  end

  payload[:_source] = 'updated_at'

  self.new.merge payload
end