Class: Chewy::Query

Inherits:
Object show all
Includes:
Loading, Pagination, Enumerable
Defined in:
lib/chewy/query.rb,
lib/chewy/query/compose.rb,
lib/chewy/query/filters.rb,
lib/chewy/query/loading.rb,
lib/chewy/query/criteria.rb,
lib/chewy/query/nodes/or.rb,
lib/chewy/query/nodes/and.rb,
lib/chewy/query/nodes/not.rb,
lib/chewy/query/nodes/raw.rb,
lib/chewy/query/nodes/base.rb,
lib/chewy/query/nodes/bool.rb,
lib/chewy/query/nodes/expr.rb,
lib/chewy/query/pagination.rb,
lib/chewy/query/nodes/equal.rb,
lib/chewy/query/nodes/field.rb,
lib/chewy/query/nodes/query.rb,
lib/chewy/query/nodes/range.rb,
lib/chewy/query/nodes/exists.rb,
lib/chewy/query/nodes/prefix.rb,
lib/chewy/query/nodes/regexp.rb,
lib/chewy/query/nodes/script.rb,
lib/chewy/query/nodes/missing.rb,
lib/chewy/query/nodes/has_child.rb,
lib/chewy/query/nodes/match_all.rb,
lib/chewy/query/nodes/has_parent.rb,
lib/chewy/query/nodes/has_relation.rb,
lib/chewy/query/pagination/kaminari.rb,
lib/chewy/query/pagination/will_paginate.rb

Overview

Query allows you to create ES search requests with convenient chainable DSL. Queries are lazy evaluated and might be merged. The same DSL is used for whole index or individual types query build.

UsersIndex.filter{ age < 42 }.query(text: {name: 'Alex'}).limit(20)
UsersIndex::User.filter{ age < 42 }.query(text: {name: 'Alex'}).limit(20)

Defined Under Namespace

Modules: Compose, Loading, Nodes, Pagination Classes: Criteria, Filters

Constant Summary collapse

RESULT_MERGER =
lambda do |key, old_value, new_value|
  if old_value.is_a?(Hash) && new_value.is_a?(Hash)
    old_value.merge(new_value, &RESULT_MERGER)
  elsif new_value.is_a?(Array) && new_value.count > 1
    new_value
  else
    old_value.is_a?(Array) ? new_value : new_value.first
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Pagination

#total

Methods included from Loading

#load, #preload

Constructor Details

#initialize(index, options = {}) ⇒ Query

Returns a new instance of Query.



34
35
36
37
38
39
# File 'lib/chewy/query.rb', line 34

def initialize index, options = {}
  @index, @options = index, options
  @types = Array.wrap(options.delete(:types))
  @criteria = Criteria.new
  reset
end

Instance Attribute Details

#criteriaObject (readonly)

Returns the value of attribute criteria.



32
33
34
# File 'lib/chewy/query.rb', line 32

def criteria
  @criteria
end

#indexObject (readonly)

Returns the value of attribute index.



32
33
34
# File 'lib/chewy/query.rb', line 32

def index
  @index
end

#optionsObject (readonly)

Returns the value of attribute options.



32
33
34
# File 'lib/chewy/query.rb', line 32

def options
  @options
end

Instance Method Details

#==(other) ⇒ Object

Comparation with other query or collection If other is collection - search request is executed and result is used for comparation

UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}) # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Johny'}).to_a # => true
UsersIndex.filter(term: {name: 'Johny'}) == UsersIndex.filter(term: {name: 'Winnie'}) # => false


49
50
51
52
53
54
55
# File 'lib/chewy/query.rb', line 49

def == other
  super || if other.is_a?(self.class)
    other.criteria == criteria
  else
    to_a == other
  end
end

#aggregations(params = nil) ⇒ Object Also known as: aggs

Sets elasticsearch aggregations search request param

UsersIndex.filter{ name == 'Johny' }.aggregations(category_id: {terms: {field: 'category_ids'}})
   # => {body: {
          query: {...},
          aggregations: {
            terms: {
              field: 'category_ids'
            }
          }
        }}


496
497
498
499
500
501
502
# File 'lib/chewy/query.rb', line 496

def aggregations params = nil
  if params
    chain { criteria.update_aggregations params }
  else
    _response['aggregations'] || {}
  end
end

#boost_factor(factor, options = {}) ⇒ Object

Adds a boost factor to the search request. All scores are added to the search request and combinded according to boost_mode and score_mode

This probably only makes sense if you specifiy a filter for the boost factor as well

UsersIndex.boost_factor(23, filter: { term: { foo: :bar} })
    # => {body:
           query: {
             function_score: {
               query: { ...},
               functions: [{
                 boost_factor: 23,
                 filter: { term: { foo: :bar } }
               }]
             } } }


385
386
387
388
# File 'lib/chewy/query.rb', line 385

def boost_factor(factor, options = {})
  scoring = options.merge(boost_factor: factor.to_i)
  chain { criteria.update_scores scoring }
end

#boost_mode(value) ⇒ Object

Sets the boost mode for custom scoring/boosting. Not used if no score functions are specified Possible values:

  • :multiply Default value. Query score and function result are multiplied.

    Ex:

    UsersIndex.boost_mode('multiply').script_score('doc['boost'].value')
      # => {body: {query: function_score: {
        query: {...},
        boost_mode: 'multiply',
        functions: [ ... ]
      }}}
    
  • :replace Only function result is used, query score is ignored.

  • :sum Query score and function score are added.

  • :avg Average of query and function score.

  • :max Max of query and function score.

  • :min Min of query and function score.

Default value for :boost_mode might be changed with Chewy.score_mode config option.



678
679
680
# File 'lib/chewy/query.rb', line 678

def boost_mode value
  chain { criteria.update_options boost_mode: value }
end

#decay(function, field, options = {}) ⇒ Object

Add a decay scoring to the search. All scores are added to the search request and combinded according to boost_mode and score_mode

The parameters have default values, but those may not be very useful for most applications.

UsersIndex.decay(
             :gauss,
             :field,
             origin: '11, 12',
             scale: '2km',
             offset: '5km',
             decay: 0.4,
             filter: { foo: :bar})
    # => {body:
           query: {
             gauss: {
               query: { ...},
               functions: [{
                 gauss: {
                   field: {
                     origin: '11, 12',
                     scale: '2km',
                     offset: '5km',
                     decay: 0.4
                   }
                 },
                 filter: { foo: :bar }
               }]
             } } }


476
477
478
479
480
481
482
# File 'lib/chewy/query.rb', line 476

def decay(function, field, options = {})
  field_options = options.extract!(:origin, :scale, :offset, :decay).delete_if { |_, v| v.nil? }
  scoring = options.merge(function => {
    field => field_options
  })
  chain { criteria.update_scores scoring }
end

#delete_allObject

Deletes all records matching a query.

UsersIndex.delete_all
UsersIndex.filter{ age <= 42 }.delete_all
UsersIndex::User.delete_all
UsersIndex::User.filter{ age <= 42 }.delete_all


842
843
844
845
846
847
# File 'lib/chewy/query.rb', line 842

def delete_all
  request = chain { criteria.update_options simple: true }.send(:_request)
  ActiveSupport::Notifications.instrument 'delete_query.chewy', request: request, index: index do
    index.client.delete_by_query(request)
  end
end

#explain(value = nil) ⇒ Object

Adds explain parameter to search request.

UsersIndex.filter(term: {name: 'Johny'}).explain
UsersIndex.filter(term: {name: 'Johny'}).explain(true)
UsersIndex.filter(term: {name: 'Johny'}).explain(false)

Calling explain without any arguments sets explanation flag to true. With explain: true, every result object has _explanation method

UsersIndex::User.filter(term: {name: 'Johny'}).explain.first._explanation # => {...}


69
70
71
# File 'lib/chewy/query.rb', line 69

def explain value = nil
  chain { criteria.update_request_options explain: (value.nil? ? true : value) }
end

#facets(params = nil) ⇒ Object

Adds facets section to the search request. All the chained facets a merged and added to the search request

UsersIndex.facets(tags: {terms: {field: 'tags'}}).facets(ages: {terms: {field: 'age'}})
  # => {body: {
         query: {...},
         facets: {tags: {terms: {field: 'tags'}}, ages: {terms: {field: 'age'}}}
       }}

If called parameterless - returns result facets from ES performing request. Returns empty hash if no facets was requested or resulted.



338
339
340
341
342
343
344
# File 'lib/chewy/query.rb', line 338

def facets params = nil
  if params
    chain { criteria.update_facets params }
  else
    _response['facets'] || {}
  end
end

#field_value_factor(settings, options = {}) ⇒ Object

Add a field value scoring to the search. All scores are added to the search request and combinded according to boost_mode and score_mode

This function is only available in Elasticsearch 1.2 and greater

UsersIndex.field_value_factor(
             {
               field: :boost,
               factor: 1.2,
               modifier: :sqrt
             }, filter: { foo: :bar})
    # => {body:
           query: {
             function_score: {
               query: { ...},
               functions: [{
                 field_value_factor: {
                   field: :boost,
                   factor: 1.2,
                   modifier: :sqrt
                 },
                 filter: { foo: :bar }
               }]
             } } }


440
441
442
443
# File 'lib/chewy/query.rb', line 440

def field_value_factor(settings, options = {})
  scoring = options.merge(field_value_factor: settings)
  chain { criteria.update_scores scoring }
end

#filter(params = nil, &block) ⇒ Object

Adds one or more filter to the search request Internally filters are stored as an array While the full query compilation this array compiles according to :filter_mode option value

By default it joins inside and filter See #filter_mode chainable method for more info.

Also this method supports block DSL. See Chewy::Query::Filters for more info.

UsersIndex.filter(term: {name: 'Johny'}).filter(range: {age: {lte: 42}})
UsersIndex::User.filter(term: {name: 'Johny'}).filter(range: {age: {lte: 42}})
UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }
  # => {body: {query: {filtered: {
         query: {...},
         filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
       }}}}

If only one filter was specified, it will become a result filter as is, without joining.

UsersIndex.filter(term: {name: 'Johny'})
  # => {body: {query: {filtered: {
         query: {...},
         filter: {term: {name: 'Johny'}}
       }}}}


609
610
611
612
# File 'lib/chewy/query.rb', line 609

def filter params = nil, &block
  params = Filters.new(&block).__render__ if block
  chain { criteria.update_filters params }
end

#filter_mode(value) ⇒ Object

Sets query compilation mode for search request. Not used if only one filter for search is specified. Possible values:

  • :and Default value. Filter compiles into an and filter.

    Ex:

    UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }
      # => {body: {query: {filtered: {
             query: {...},
             filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
           }}}}
    
  • :or Filter compiles into an or filter.

    Ex:

    UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:or)
      # => {body: {query: {filtered: {
             query: {...},
             filter: {or: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
           }}}}
    
  • :must Filter compiles into a bool must filter.

    Ex:

    UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:must)
      # => {body: {query: {filtered: {
             query: {...},
             filter: {bool: {must: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
           }}}}
    
  • :should Filter compiles into a bool should filter.

    Ex:

    UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode(:should)
      # => {body: {query: {filtered: {
             query: {...},
             filter: {bool: {should: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
           }}}}
    
  • Any acceptable minimum_should_match value (1, ‘2’, ‘75%’) Filter compiles into bool should filter with minimum_should_match set.

    Ex:

    UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }.filter_mode('50%')
      # => {body: {query: {filtered: {
             query: {...},
             filter: {bool: {
               should: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
               minimum_should_match: '50%'
             }}
           }}}}
    

Default value for :filter_mode might be changed with Chewy.filter_mode config option.

Chewy.filter_mode = :should
Chewy.filter_mode = '50%'


211
212
213
# File 'lib/chewy/query.rb', line 211

def filter_mode value
  chain { criteria.update_options filter_mode: value }
end

#find(*ids) ⇒ Object

Deletes all records matching a query.

UsersIndex.find(42)
UsersIndex.filter{ age <= 42 }.find(42)
UsersIndex::User.find(42)
UsersIndex::User.filter{ age <= 42 }.find(42)

In all the previous examples find will return a single object. To get a collection - pass an array of ids.

UsersIndex::User.find(42, 7, 3) # array of objects with ids in [42, 7, 3]
UsersIndex::User.find([8, 13])  # array of objects with ids in [8, 13]
UsersIndex::User.find([42])     # array of the object with id == 42


863
864
865
866
867
868
# File 'lib/chewy/query.rb', line 863

def find *ids
  results = chain { criteria.update_options simple: true }.filter { _id == ids.flatten }.to_a

  raise Chewy::DocumentNotFound.new("Could not find documents for ids #{ids.flatten}") if results.empty?
  ids.one? && !ids.first.is_a?(Array) ? results.first : results
end

#highlight(value) ⇒ Object

Elasticsearch highlight query option support

UsersIndex.query(...).highlight(fields: { ... })


305
306
307
# File 'lib/chewy/query.rb', line 305

def highlight value
  chain { criteria.update_request_options highlight: value }
end

#limit(value) ⇒ Object

Sets elasticsearch size search request param Default value is set in the elasticsearch and is 10.

UsersIndex.filter{ name == 'Johny' }.limit(100)
   # => {body: {
          query: {...},
          size: 100
        }}


285
286
287
# File 'lib/chewy/query.rb', line 285

def limit value
  chain { criteria.update_request_options size: Integer(value) }
end

#merge(other) ⇒ Object

Merges two queries. Merges all the values in criteria with the same rules as values added manually.

scope1 = UsersIndex.filter{ name == 'Johny' }
scope2 = UsersIndex.filter{ age <= 42 }
scope3 = UsersIndex.filter{ name == 'Johny' }.filter{ age <= 42 }

scope1.merge(scope2) == scope3 # => true


831
832
833
# File 'lib/chewy/query.rb', line 831

def merge other
  chain { criteria.merge!(other.criteria) }
end

#min_score(value) ⇒ Object

Elasticsearch minscore option support

UsersIndex.query(…).min_score(0.5)



321
322
323
# File 'lib/chewy/query.rb', line 321

def min_score value
  chain { criteria.update_request_options min_score: value }
end

#noneObject

Marks the criteria as having zero records. This scope always returns empty array without touching the elasticsearch server. All the chained calls of methods don’t affect the result

UsersIndex.none.to_a
  # => []
UsersIndex.query(text: {name: 'Johny'}).none.to_a
  # => []
UsersIndex.none.query(text: {name: 'Johny'}).to_a
  # => []


537
538
539
# File 'lib/chewy/query.rb', line 537

def none
  chain { criteria.update_options none: true }
end

#offset(value) ⇒ Object

Sets elasticsearch from search request param

UsersIndex.filter{ name == 'Johny' }.offset(300)
   # => {body: {
          query: {...},
          from: 300
        }}


297
298
299
# File 'lib/chewy/query.rb', line 297

def offset value
  chain { criteria.update_request_options from: Integer(value) }
end

#only(*params) ⇒ Object

Sets search request field list

UsersIndex.only(:first_name, :last_name).only(:age)
  # => {body: {
         query: {...},
         fields: ['first_name', 'last_name', 'age']
       }}


754
755
756
# File 'lib/chewy/query.rb', line 754

def only *params
  chain { criteria.update_fields params }
end

#only!(*params) ⇒ Object

Cleans up previous search field list and sets the new one

UsersIndex.only(:first_name, :last_name).only!(:age)
  # => {body: {
         query: {...},
         fields: ['age']
       }}


766
767
768
# File 'lib/chewy/query.rb', line 766

def only! *params
  chain { criteria.update_fields params, purge: true }
end

#order(*params) ⇒ Object

Sets search request sorting

UsersIndex.order(:first_name, :last_name).order(age: :desc).order(price: {order: :asc, mode: :avg})
  # => {body: {
         query: {...},
         sort: ['first_name', 'last_name', {age: 'desc'}, {price: {order: 'asc', mode: 'avg'}}]
       }}


730
731
732
# File 'lib/chewy/query.rb', line 730

def order *params
  chain { criteria.update_sort params }
end

#post_filter(params = nil, &block) ⇒ Object

Adds one or more post_filter to the search request Internally post_filters are stored as an array While the full query compilation this array compiles according to :post_filter_mode option value

By default it joins inside and filter See #post_filter_mode chainable method for more info.

Also this method supports block DSL. See Chewy::Query::Filters for more info.

UsersIndex.post_filter(term: {name: 'Johny'}).post_filter(range: {age: {lte: 42}})
UsersIndex::User.post_filter(term: {name: 'Johny'}).post_filter(range: {age: {lte: 42}})
UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }
  # => {body: {
         post_filter: {and: [{term: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}
       }}

If only one post_filter was specified, it will become a result post_filter as is, without joining.

UsersIndex.post_filter(term: {name: 'Johny'})
  # => {body: {
         post_filter: {term: {name: 'Johny'}}
       }}


640
641
642
643
# File 'lib/chewy/query.rb', line 640

def post_filter params = nil, &block
  params = Filters.new(&block).__render__ if block
  chain { criteria.update_post_filters params }
end

#post_filter_mode(value) ⇒ Object

Acts the same way as filter_mode, but used for post_filter. Note that it fallbacks by default to Chewy.filter_mode if Chewy.post_filter_mode is nil.

UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode(:and)
UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode(:should)
UsersIndex.post_filter{ name == 'Johny' }.post_filter{ age <= 42 }.post_filter_mode('50%')


223
224
225
# File 'lib/chewy/query.rb', line 223

def post_filter_mode value
  chain { criteria.update_options post_filter_mode: value }
end

#query(params) ⇒ Object

Adds one or more query to the search request Internally queries are stored as an array While the full query compilation this array compiles according to :query_mode option value

By default it joines inside must query See #query_mode chainable method for more info.

UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
UsersIndex::User.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
  # => {body: {
         query: {bool: {must: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
       }}

If only one query was specified, it will become a result query as is, without joining.

UsersIndex.query(text: {name: 'Johny'})
  # => {body: {
         query: {text: {name: 'Johny'}}
       }}


577
578
579
# File 'lib/chewy/query.rb', line 577

def query params
  chain { criteria.update_queries params }
end

#query_mode(value) ⇒ Object

Sets query compilation mode for search request. Not used if only one filter for search is specified. Possible values:

  • :must Default value. Query compiles into a bool must query.

    Ex:

    UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}})
      # => {body: {
             query: {bool: {must: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
           }}
    
  • :should Query compiles into a bool should query.

    Ex:

    UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(:should)
      # => {body: {
             query: {bool: {should: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
           }}
    
  • Any acceptable minimum_should_match value (1, ‘2’, ‘75%’) Query compiles into a bool should query with minimum_should_match set.

    Ex:

    UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode('50%')
      # => {body: {
             query: {bool: {
               should: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
               minimum_should_match: '50%'
             }}
           }}
    
  • :dis_max Query compiles into a dis_max query.

    Ex:

    UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(:dis_max)
      # => {body: {
             query: {dis_max: {queries: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}]}}
           }}
    
  • Any Float value (0.0, 0.7, 1.0) Query compiles into a dis_max query with tie_breaker option set.

    Ex:

    UsersIndex.query(text: {name: 'Johny'}).query(range: {age: {lte: 42}}).query_mode(0.7)
      # => {body: {
             query: {dis_max: {
               queries: [{text: {name: 'Johny'}}, {range: {age: {lte: 42}}}],
               tie_breaker: 0.7
             }}
           }}
    

Default value for :query_mode might be changed with Chewy.query_mode config option.

Chewy.query_mode = :dis_max
Chewy.query_mode = '50%'


139
140
141
# File 'lib/chewy/query.rb', line 139

def query_mode value
  chain { criteria.update_options query_mode: value }
end

#random_score(seed = Time.now, options = {}) ⇒ Object

Adds a random score to the search request. All scores are added to the search request and combinded according to boost_mode and score_mode

This probably only makes sense if you specifiy a filter for the random score as well.

If you do not pass in a seed value, Time.now will be used

UsersIndex.random_score(23, filter: { foo: :bar})
    # => {body:
           query: {
             function_score: {
               query: { ...},
               functions: [{
                 random_score: { seed: 23 },
                 filter: { foo: :bar }
               }]
             } } }


409
410
411
412
# File 'lib/chewy/query.rb', line 409

def random_score(seed = Time.now, options = {})
  scoring = options.merge(random_score: { seed: seed.to_i })
  chain { criteria.update_scores scoring }
end

#reorder(*params) ⇒ Object

Cleans up previous search sorting and sets the new one

UsersIndex.order(:first_name, :last_name).order(age: :desc).reorder(price: {order: :asc, mode: :avg})
  # => {body: {
         query: {...},
         sort: [{price: {order: 'asc', mode: 'avg'}}]
       }}


742
743
744
# File 'lib/chewy/query.rb', line 742

def reorder *params
  chain { criteria.update_sort params, purge: true }
end

#rescore(value) ⇒ Object

Elasticsearch rescore query option support

UsersIndex.query(...).rescore(query: { ... })


313
314
315
# File 'lib/chewy/query.rb', line 313

def rescore value
  chain { criteria.update_request_options rescore: value }
end

#score_mode(value) ⇒ Object

Sets the scoring mode for combining function scores/boosts Not used if no score functions are specified. Possible values:

  • :multiply Default value. Scores are multiplied.

    Ex:

    UsersIndex.score_mode('multiply').script_score('doc['boost'].value')
      # => {body: {query: function_score: {
        query: {...},
        score_mode: 'multiply',
        functions: [ ... ]
      }}}
    
  • :sum Scores are summed.

  • :avg Scores are averaged.

  • :first The first function that has a matching filter is applied.

  • :max Maximum score is used.

  • :min Minimum score is used

Default value for :score_mode might be changed with Chewy.score_mode config option.

Chewy.score_mode = :first


718
719
720
# File 'lib/chewy/query.rb', line 718

def score_mode value
  chain { criteria.update_options score_mode: value }
end

#script_score(script, options = {}) ⇒ Object

Adds a script function to score the search request. All scores are added to the search request and combinded according to boost_mode and score_mode

UsersIndex.script_score("doc['boost'].value", filter: { term: {foo: :bar} })
    # => {body:
           query: {
             function_score: {
               query: { ...},
               functions: [{
                 script_score: {
                    script: "doc['boost'].value"
                  },
                  filter: { term: { foo: :bar } }
                 }
               }]
             } } }


363
364
365
366
# File 'lib/chewy/query.rb', line 363

def script_score(script, options = {})
  scoring = options.merge(script_score: { script: script })
  chain { criteria.update_scores scoring }
end

#strategy(value = nil) ⇒ Object

Setups strategy for top-level filtered query

UsersIndex.filter { name == 'Johny'}.strategy(:leap_frog)
 # => {body: {
        query: { filtered: {
          filter: { term: { name: 'Johny' } },
          strategy: 'leap_frog'
        } }
      }}


551
552
553
# File 'lib/chewy/query.rb', line 551

def strategy value = nil
  chain { criteria.update_options strategy: value }
end

#suggest(params = nil) ⇒ Object

Sets elasticsearch suggest search request param

UsersIndex.suggest(name: {text: 'Joh', term: {field: 'name'}})
   # => {body: {
          query: {...},
          suggest: {
            text: 'Joh',
            term: {
              field: 'name'
            }
          }
        }}


518
519
520
521
522
523
524
# File 'lib/chewy/query.rb', line 518

def suggest params = nil
  if params
    chain { criteria.update_suggest params }
  else
    _response['suggest'] || {}
  end
end

#timed_outObject

Returns request timed_out as reported by elasticsearch

The timed_out value tells us whether the query timed out or not.

By default, search requests do not timeout. If low response times are more important to you than complete results, you can specify a timeout as 10 or “10ms” (10 milliseconds), or “1s” (1 second). See #timeout method.

UsersIndex.query(...).filter(...).timed_out


888
889
890
# File 'lib/chewy/query.rb', line 888

def timed_out
  _response['timed_out']
end

#timeout(value) ⇒ Object

A search timeout, bounding the search request to be executed within the specified time value and bail with the hits accumulated up to that point when expired. Defaults to no timeout.

By default, the coordinating node waits to receive a response from all shards. If one node is having trouble, it could slow down the response to all search requests.

The timeout parameter tells the coordinating node how long it should wait before giving up and just returning the results that it already has. It can be better to return some results than none at all.

The response to a search request will indicate whether the search timed out and how many shards responded successfully:

...
"timed_out":     true,
"_shards": {
    "total":      5,
    "successful": 4,
    "failed":     1
},
...

The primary shard assigned to perform the index operation might not be available when the index operation is executed. Some reasons for this might be that the primary shard is currently recovering from a gateway or undergoing relocation. By default, the index operation will wait on the primary shard to become available for up to 1 minute before failing and responding with an error. The timeout parameter can be used to explicitly specify how long it waits.

UsersIndex.timeout("5000ms")

Timeout is not a circuit breaker.

It should be noted that this timeout does not halt the execution of the query, it merely tells the coordinating node to return the results collected so far and to close the connection. In the background, other shards may still be processing the query even though results have been sent.

Use the timeout because it is important to your SLA, not because you want to abort the execution of long running queries.



272
273
274
# File 'lib/chewy/query.rb', line 272

def timeout value
  chain { criteria.update_request_options timeout: value }
end

#tookObject

Returns request total time elapsed as reported by elasticsearch

UsersIndex.query(...).filter(...).took


874
875
876
# File 'lib/chewy/query.rb', line 874

def took
  _response['took']
end

#types(*params) ⇒ Object

Specify types participating in the search result Works via types filter. Always merged with another filters with the and filter.

UsersIndex.types(:admin, :manager).filters{ name == 'Johny' }.filters{ age <= 42 }
  # => {body: {query: {filtered: {
         query: {...},
         filter: {and: [
           {or: [
             {type: {value: 'admin'}},
             {type: {value: 'manager'}}
           ]},
           {term: {name: 'Johny'}},
           {range: {age: {lte: 42}}}
         ]}
       }}}}

UsersIndex.types(:admin, :manager).filters{ name == 'Johny' }.filters{ age <= 42 }.filter_mode(:or)
  # => {body: {query: {filtered: {
         query: {...},
         filter: {and: [
           {or: [
             {type: {value: 'admin'}},
             {type: {value: 'manager'}}
           ]},
           {or: [
             {term: {name: 'Johny'}},
             {range: {age: {lte: 42}}}
           ]}
         ]}
       }}}}


802
803
804
805
806
807
808
# File 'lib/chewy/query.rb', line 802

def types *params
  if params.any?
    chain { criteria.update_types params }
  else
    @types
  end
end

#types!(*params) ⇒ Object

Acts the same way as types, but cleans up previously set types

UsersIndex.types(:admin).types!(:manager)
  # => {body: {query: {filtered: {
         query: {...},
         filter: {type: {value: 'manager'}}
       }}}}


818
819
820
# File 'lib/chewy/query.rb', line 818

def types! *params
  chain { criteria.update_types params, purge: true }
end