Class: Chewy::Search::Request

Inherits:
Object
  • Object
show all
Includes:
Scoping, Scrolling, Enumerable
Defined in:
lib/chewy/search/request.rb

Overview

Note:

The class tries to be as immutable as possible, so most of the methods return a new instance of the class.

The main request DSL class. Supports multiple index requests. Supports ES5 search API and query DSL.

Examples:

scope = Chewy::Search::Request.new(PlacesIndex)
# => <Chewy::Search::Request {:index=>["places"], :body=>{}}>
scope.limit(20)
# => <Chewy::Search::Request {:index=>["places"], :body=>{:size=>20}}>
scope.order(:name).offset(10)
# => <Chewy::Search::Request {:index=>["places"], :body=>{:sort=>["name"], :from=>10}}>

See Also:

Constant Summary collapse

UNDEFINED =
Class.new.freeze
EVERFIELDS =
%w[_index _type _id _parent _routing].freeze
DELEGATED_METHODS =
%i[
  query filter post_filter order reorder docvalue_fields
  track_scores track_total_hits request_cache explain version profile
  search_type preference limit offset terminate_after
  timeout min_score source stored_fields search_after
  load script_fields suggest aggs aggregations none
  indices_boost rescore highlight total total_count
  total_entries indices types delete_all count exists?
  exist? find pluck scroll_batches scroll_hits
  scroll_results scroll_wrappers ignore_unavailable
].to_set.freeze
DEFAULT_BATCH_SIZE =
1000
DEFAULT_PLUCK_BATCH_SIZE =
10_000
DEFAULT_SCROLL =
'1m'.freeze
FIELD_STORAGES =

An array of storage names that are modifying returned fields in hits

%i[
  source docvalue_fields script_fields stored_fields
].freeze
EXTRA_STORAGES =

An array of storage names that are not related to hits at all.

%i[aggs suggest].freeze
WHERE_STORAGES =

An array of storage names that are changing the returned hist collection in any way.

%i[
  query filter post_filter none min_score rescore indices_boost
].freeze

Chainable request modifications collapse

Scopes manipulation collapse

Additional actions collapse

Instance Method Summary collapse

Methods included from Scrolling

#scroll_batches, #scroll_hits, #scroll_objects, #scroll_wrappers

Methods included from Scoping

#scoping

Constructor Details

#initialize(*indexes) ⇒ Request

The class is initialized with the list of chewy indexes, which are later used to compose requests. Any symbol/string passed is treated as an index identifier.

Examples:

Chewy::Search::Request.new(:places)
# => <Chewy::Search::Request {:index=>["places"], :body=>{}}>
Chewy::Search::Request.new(PlacesIndex)
# => <Chewy::Search::Request {:index=>["places"], :body=>{}}>
Chewy::Search::Request.new(UsersIndex, PlacesIndex)
# => <Chewy::Search::Request {:index=>["users", "places"], :body=>{}}>

Parameters:



67
68
69
70
71
# File 'lib/chewy/search/request.rb', line 67

def initialize(*indexes)
  parameters.modify!(:indices) do
    replace!(indices: indexes)
  end
end

Instance Method Details

#==(other) ⇒ true, false

Compare two scopes or scope with a collection of wrappers. If other is a collection it performs the request to fetch data from ES.

Examples:

PlacesIndex.limit(10) == PlacesIndex.limit(10) # => true
PlacesIndex.limit(10) == PlacesIndex.limit(10).to_a # => true
PlacesIndex.limit(10) == PlacesIndex.limit(10).objects # => true

PlacesIndex.limit(10) == UsersIndex.limit(10) # => false
PlacesIndex.limit(10) == UsersIndex.limit(10).to_a # => false

PlacesIndex.limit(10) == Object.new # => false

Parameters:

  • other (Object)

    any object

Returns:

  • (true, false)

    the result of comparison



95
96
97
# File 'lib/chewy/search/request.rb', line 95

def ==(other)
  super || other.is_a?(Chewy::Search::Request) ? compare_internals(other) : to_a == other
end

#aggs(value) ⇒ Chewy::Search::Request #aggsHash Also known as: aggregations

A dual-purpose method.

Overloads:



703
704
705
706
707
708
709
# File 'lib/chewy/search/request.rb', line 703

def aggs(value = UNDEFINED)
  if value == UNDEFINED
    response.aggs
  else
    modify(:aggs) { update!(value) }
  end
end

#and(other) ⇒ Chewy::Search::Request

Takes query, filter, post_filter from the passed scope and performs QueryProxy#and operation for each of them. Unlike merge, every other parameter is kept unmerged (values from the first scope are used in the result scope).

Examples:

scope1 = PlacesIndex.filter(term: {name: 'Moscow'}).query(match: {name: 'London'})
scope2 = PlacesIndex.filter.not(term: {name: 'Berlin'}).query(match: {name: 'Washington'})
scope1.and(scope2)
# => <PlacesIndex::Query {..., :body=>{:query=>{:bool=>{
#      :must=>[{:match=>{:name=>"London"}}, {:match=>{:name=>"Washington"}}],
#      :filter=>{
#        :bool=>{:must=>[{:term=>{:name=>"Moscow"}}, {:bool=>{:must_not=>{:term=>{:name=>"Berlin"}}}}]}
#      }
#    }}}}>

Parameters:

Returns:

See Also:



792
793
794
795
796
797
798
# File 'lib/chewy/search/request.rb', line 792

%i[and or not].each do |name|
  define_method name do |other|
    %i[query filter post_filter].inject(self) do |scope, parameter_name|
      scope.send(parameter_name).send(name, other.parameters[parameter_name].value)
    end
  end
end

#countInteger

Returns total count of hits for the request. If the request was already performed - it uses the total value, otherwise it executes a fast count request.

Returns:

  • (Integer)

    total hits count



829
830
831
832
833
834
835
836
837
# File 'lib/chewy/search/request.rb', line 829

def count
  if performed?
    total
  else
    Chewy.client.count(only(WHERE_STORAGES).render)['count']
  end
rescue Elasticsearch::Transport::Transport::Errors::NotFound
  0
end

#delete_all(refresh: true) ⇒ Hash

Note:

The result hash is different for different API used.

Deletes all the documents from the specified scope it uses delete_by_query

Parameters:

  • refresh (true, false) (defaults to: true)

    field names

Returns:

  • (Hash)

    the result of query execution

See Also:



956
957
958
959
960
961
962
# File 'lib/chewy/search/request.rb', line 956

def delete_all(refresh: true)
  request_body = only(WHERE_STORAGES).render.merge(refresh: refresh)
  ActiveSupport::Notifications.instrument 'delete_query.chewy', notification_payload(request: request_body) do
    request_body[:body] = {query: {match_all: {}}} if request_body[:body].empty?
    Chewy.client.delete_by_query(request_body)
  end
end

#docvalue_fields(*values) ⇒ Chewy::Search::Request

Modifies docvalue_fields request parameter. Updates the storage on every call.

Examples:

PlacesIndex.docvalue_fields(:name).docvalue_fields(:population, :coordinates)
# => <PlacesIndex::Query {..., :body=>{:docvalue_fields=>["name", "population", "coordinates"]}}>

Parameters:

  • values (Array<String, Symbol>)

    field names

Returns:

See Also:



292
293
294
295
296
# File 'lib/chewy/search/request.rb', line 292

%i[order docvalue_fields].each do |name|
  define_method name do |value, *values|
    modify(name) { update!([value, *values]) }
  end
end

#except(*values) ⇒ Chewy::Search::Request

Returns a new scope containing all the storages except specified.

Examples:

PlacesIndex.limit(10).offset(10).order(:name).only(:offset, :order)
# => <PlacesIndex::Query {..., :body=>{:from=>10, :sort=>["name"]}}>

Parameters:

  • values (Array<String, Symbol>)

Returns:



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

def except(*values)
  chain { parameters.except!(values.flatten(1)) }
end

#exists?true, false Also known as: exist?

Checks if any of the document exist for this request. If the request was already performed - it uses the total, otherwise it executes a fast request to check existence.

Returns:

  • (true, false)

    wether hits exist or not



844
845
846
847
848
849
850
# File 'lib/chewy/search/request.rb', line 844

def exists?
  if performed?
    total != 0
  else
    limit(0).terminate_after(1).total != 0
  end
end

#explain(value = true) ⇒ Chewy::Search::Request

Replaces the value of the explain parameter with the provided value.

Examples:

PlacesIndex.explain
# => <PlacesIndex::Query {..., :body=>{:explain=>true}}>
PlacesIndex.explain.explain(false)
# => <PlacesIndex::Query {:index=>["places"]}>

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end

#filter(query_hash) ⇒ Chewy::Search::Request #filter { ... } ⇒ Chewy::Search::Request #filterChewy::Search::QueryProxy

Adds filter context of the query parameter at the search request body.

Overloads:

Returns:

See Also:



261
262
263
264
265
266
267
268
269
# File 'lib/chewy/search/request.rb', line 261

%i[query filter post_filter].each do |name|
  define_method name do |query_hash = UNDEFINED, &block|
    if block || query_hash != UNDEFINED
      modify(name) { must(block || query_hash) }
    else
      Chewy::Search::QueryProxy.new(name, self)
    end
  end
end

#find(id) ⇒ Chewy::Index #find(*ids) ⇒ Array<Chewy::Index>

Finds documents with specified ids for the current request scope.

Overloads:

  • #find(id) ⇒ Chewy::Index

    If single id is passed - it returns a single object.

    Parameters:

    • id (Integer, String)

      id of the desired document

    Returns:

  • #find(*ids) ⇒ Array<Chewy::Index>

    If several field are passed - it returns an array of wrappers. Respect the amount of passed ids and if it is more than the default batch size - uses scroll API to retrieve everything.

    Parameters:

    • ids (Array<Integer, String>)

      ids of the desired documents

    Returns:

Raises:



896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'lib/chewy/search/request.rb', line 896

def find(*ids)
  return super if block_given?

  ids = ids.flatten(1).map(&:to_s)
  scope = except(EXTRA_STORAGES).filter(ids: {values: ids})

  results = if ids.size > DEFAULT_BATCH_SIZE
    scope.scroll_wrappers
  else
    scope.limit(ids.size)
  end.to_a

  if ids.size != results.size
    missing_ids = ids - results.map(&:id).map(&:to_s)
    raise Chewy::DocumentNotFound, "Could not find documents for ids: #{missing_ids.to_sentence}"
  end
  results.one? ? results.first : results
end

#firstChewy::Index #first(limit) ⇒ Array<Chewy::Index>

Return first wrapper object or a collection of first N wrapper objects if the argument is provided. Tries to use cached results of possible. If the amount of cached results is insufficient - performs a new request.

Overloads:

  • #firstChewy::Index

    If nothing is passed - it returns a single object.

    Returns:

  • #first(limit) ⇒ Array<Chewy::Index>

    If limit is provided - it returns the limit amount or less of wrapper objects.

    Parameters:

    • limit (Integer)

      amount of requested results

    Returns:



869
870
871
872
873
874
875
876
877
878
# File 'lib/chewy/search/request.rb', line 869

def first(limit = UNDEFINED)
  request_limit = limit == UNDEFINED ? 1 : limit

  if performed? && (request_limit <= size || size == total)
    limit == UNDEFINED ? wrappers.first : wrappers.first(limit)
  else
    result = except(EXTRA_STORAGES).limit(request_limit).to_a
    limit == UNDEFINED ? result.first : result
  end
end

#highlight(value) ⇒ Chewy::Search::Request

Add a highlight configuration to the request. Further call values are merged to the storage hash.

Examples:

PlacesIndex
  .highlight(fields: {description: {type: 'plain'}})
  .highlight(pre_tags: ['<em>'], post_tags: ['</em>'])
# => <PlacesIndex::Query {..., :body=>{:highlight=>{
#      "fields"=>{:description=>{:type=>"plain"}},
#      "pre_tags"=>["<em>"], "post_tags"=>["</em>"]}}}>

Parameters:

  • value (Hash)

Returns:

See Also:



637
638
639
640
641
# File 'lib/chewy/search/request.rb', line 637

%i[script_fields indices_boost rescore highlight].each do |name|
  define_method name do |value|
    modify(name) { update!(value) }
  end
end

#ignore_unavailable(value) ⇒ Chewy::Search::Request

Replaces the value of the ignore_unavailable request part.

Examples:

PlacesIndex.ignore_unavailable(true)
<PlacesIndex::Query {..., :ignore_unavailable => true, :body=>{ ... }}>

Parameters:

  • value (true, false, nil)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#indices(value, *values) ⇒ Chewy::Search::Request

Modifies index request parameter. Updates the storage on every call. Added passed indexes to the parameter list.

Examples:

UsersIndex.indices(CitiesIndex).indices(:another)
# => <UsersIndex::Query {:index=>["another", "cities", "users"]}>

Parameters:

  • values (Array<Chewy::Index, String, Symbol>)

    index names

Returns:

See Also:



308
309
310
# File 'lib/chewy/search/request.rb', line 308

def indices(value, *values)
  modify(:indices) { update!(indices: [value, *values]) }
end

#indices_boost(value) ⇒ Chewy::Search::Request

Add an indices_boost part to the request. Further call values are merged to the storage hash.

Examples:

PlacesIndex.indices_boost(index1: 1.2, index2: 1.3).indices_boost(index1: 1.5)
# => <PlacesIndex::Query {..., :body=>{:indices_boost=>[{"index2"=>1.3}, {"index1"=>1.5}]}}>

Parameters:

  • value ({String, Symbol => String, Integer, Float})

Returns:

See Also:



637
638
639
640
641
# File 'lib/chewy/search/request.rb', line 637

%i[script_fields indices_boost rescore highlight].each do |name|
  define_method name do |value|
    modify(name) { update!(value) }
  end
end

#inspectString

Includes the class name and the result of rendering.

Returns:

  • (String)


127
128
129
# File 'lib/chewy/search/request.rb', line 127

def inspect
  "<#{self.class} #{render}>"
end

#limit(value) ⇒ Chewy::Search::Request

Replaces the value of the size request part.

Examples:

PlacesIndex.limit(10)
<PlacesIndex::Query {..., :body=>{:size=>10}}>

Parameters:

  • value (String, Integer)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#load(options = nil) ⇒ Object

Stores ORM/ODM objects loading options. Options might be define per-index or be global, depends on the adapter loading implementation. Also, there are 2 loading options to select or exclude indexes from loading: only and except respectively. Options are updated on further method calls.

Examples:

PlaceIndex.load(only: 'city').load(scope: -> { active })

Parameters:

  • options (Hash) (defaults to: nil)

    adapter-specific loading options

See Also:



578
579
580
# File 'lib/chewy/search/request.rb', line 578

def load(options = nil)
  modify(:load) { update!(options) }
end

#merge(other) ⇒ Chewy::Search::Request

Merges 2 scopes by merging their parameters.

Examples:

scope1 = PlacesIndex.limit(10).offset(10)
scope2 = PlacesIndex.limit(20)
scope1.merge(scope2)
# => <PlacesIndex::Query {..., :body=>{:size=>20, :from=>10}}>
scope2.merge(scope1)
# => <PlacesIndex::Query {..., :body=>{:size=>10, :from=>10}}>

Parameters:

Returns:

See Also:

  • Parameters#merge


726
727
728
# File 'lib/chewy/search/request.rb', line 726

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

#min_score(value) ⇒ Chewy::Search::Request

Replaces the value of the min_score request part.

Examples:

PlacesIndex.min_score(2)
<PlacesIndex::Query {..., :body=>{:min_score=>2.0}}>

Parameters:

  • value (String, Integer, Float)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#none(value = true) ⇒ Chewy::Search::Request

Enables NullObject pattern for the request, doesn't perform the request, #hits are empty, #total is 0, etc.

Examples:

PlacesIndex.none.to_a
# => []
PlacesIndex.none.total
# => 0

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end

#not(other) ⇒ Chewy::Search::Request

Takes query, filter, post_filter from the passed scope and performs QueryProxy#not operation for each of them. Unlike merge, every other parameter is kept unmerged (values from the first scope are used in the result scope).

Examples:

scope1 = PlacesIndex.filter(term: {name: 'Moscow'}).query(match: {name: 'London'})
scope2 = PlacesIndex.filter.not(term: {name: 'Berlin'}).query(match: {name: 'Washington'})
scope1.not(scope2)
# => <PlacesIndex::Query {..., :body=>{:query=>{:bool=>{
#      :must=>{:match=>{:name=>"London"}}, :must_not=>{:match=>{:name=>"Washington"}},
#      :filter=>{
#        :bool=>{
#          :must=>{:term=>{:name=>"Moscow"}},
#          :must_not=>{:bool=>{:must_not=>{:term=>{:name=>"Berlin"}}}}
#        }
#      }
#    }}}}>

Parameters:

Returns:

See Also:



792
793
794
795
796
797
798
# File 'lib/chewy/search/request.rb', line 792

%i[and or not].each do |name|
  define_method name do |other|
    %i[query filter post_filter].inject(self) do |scope, parameter_name|
      scope.send(parameter_name).send(name, other.parameters[parameter_name].value)
    end
  end
end

#offset(value) ⇒ Chewy::Search::Request

Replaces the value of the from request part.

Examples:

PlacesIndex.offset(10)
<PlacesIndex::Query {..., :body=>{:from=>10}}>

Parameters:

  • value (String, Integer)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#only(*values) ⇒ Chewy::Search::Request

Returns a new scope containing only specified storages.

Examples:

PlacesIndex.limit(10).offset(10).order(:name).except(:offset, :order)
# => <PlacesIndex::Query {..., :body=>{:size=>10}}>

Parameters:

  • values (Array<String, Symbol>)

Returns:



807
808
809
# File 'lib/chewy/search/request.rb', line 807

def only(*values)
  chain { parameters.only!(values.flatten(1) + [:indices]) }
end

#or(other) ⇒ Chewy::Search::Request

Takes query, filter, post_filter from the passed scope and performs QueryProxy#or operation for each of them. Unlike merge, every other parameter is kept unmerged (values from the first scope are used in the result scope).

Examples:

scope1 = PlacesIndex.filter(term: {name: 'Moscow'}).query(match: {name: 'London'})
scope2 = PlacesIndex.filter.not(term: {name: 'Berlin'}).query(match: {name: 'Washington'})
scope1.or(scope2)
# => <PlacesIndex::Query {..., :body=>{:query=>{:bool=>{
#      :should=>[{:match=>{:name=>"London"}}, {:match=>{:name=>"Washington"}}],
#      :filter=>{
#        :bool=>{:should=>[{:term=>{:name=>"Moscow"}}, {:bool=>{:must_not=>{:term=>{:name=>"Berlin"}}}}]}
#      }
#    }}}}>

Parameters:

Returns:

See Also:



792
793
794
795
796
797
798
# File 'lib/chewy/search/request.rb', line 792

%i[and or not].each do |name|
  define_method name do |other|
    %i[query filter post_filter].inject(self) do |scope, parameter_name|
      scope.send(parameter_name).send(name, other.parameters[parameter_name].value)
    end
  end
end

#order(*values) ⇒ Chewy::Search::Request

Modifies sort request parameter. Updates the storage on every call.

Examples:

PlacesIndex.order(:name, population: {order: :asc}).order(:coordinates)
# => <PlacesIndex::Query {..., :body=>{:sort=>["name", {"population"=>{:order=>:asc}}, "coordinates"]}}>

Parameters:

  • values (Array<Hash, String, Symbol>)

    sort fields and options

Returns:

See Also:



292
293
294
295
296
# File 'lib/chewy/search/request.rb', line 292

%i[order docvalue_fields].each do |name|
  define_method name do |value, *values|
    modify(name) { update!([value, *values]) }
  end
end

#parametersChewy::Search::Parameters

Underlying parameter storage collection.



76
77
78
# File 'lib/chewy/search/request.rb', line 76

def parameters
  @parameters ||= Parameters.new
end

#performed?true, false

Returns whether or not the query has been performed.

Returns:

  • (true, false)


967
968
969
# File 'lib/chewy/search/request.rb', line 967

def performed?
  !@response.nil?
end

#pluck(field) ⇒ Array<Object> #pluck(*fields) ⇒ Array<Array<Object>>

Returns and array of values for specified fields. Uses source to restrict the list of returned fields. Fields _id, _type, _routing and _index are also supported.

Overloads:

  • #pluck(field) ⇒ Array<Object>

    If single field is passed - it returns and array of values.

    Parameters:

    • field (String, Symbol)

      field name

    Returns:

    • (Array<Object>)

      specified field values

  • #pluck(*fields) ⇒ Array<Array<Object>>

    If several field are passed - it returns an array of arrays of values.

    Parameters:

    • fields (Array<String, Symbol>)

      field names

    Returns:

    • (Array<Array<Object>>)

      specified field values



930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/chewy/search/request.rb', line 930

def pluck(*fields)
  fields = fields.flatten(1).reject(&:blank?).map(&:to_s)

  source_fields = fields - EVERFIELDS
  scope = except(FIELD_STORAGES, EXTRA_STORAGES)
    .source(source_fields.presence || false)

  hits = raw_limit_value ? scope.hits : scope.scroll_hits(batch_size: DEFAULT_PLUCK_BATCH_SIZE)
  hits.map do |hit|
    if fields.one?
      fetch_field(hit, fields.first)
    else
      fields.map do |field|
        fetch_field(hit, field)
      end
    end
  end
end

#post_filter(query_hash) ⇒ Chewy::Search::Request #post_filter { ... } ⇒ Chewy::Search::Request #post_filterChewy::Search::QueryProxy

Adds post_filter parameter to the search request body.

Overloads:

Returns:

See Also:



261
262
263
264
265
266
267
268
269
# File 'lib/chewy/search/request.rb', line 261

%i[query filter post_filter].each do |name|
  define_method name do |query_hash = UNDEFINED, &block|
    if block || query_hash != UNDEFINED
      modify(name) { must(block || query_hash) }
    else
      Chewy::Search::QueryProxy.new(name, self)
    end
  end
end

#preference(value) ⇒ Chewy::Search::Request

Replaces the value of the preference request part.

Examples:

PlacesIndex.preference(:_primary_first)
# => <PlacesIndex::Query {..., :body=>{:preference=>"_primary_first"}}>

Parameters:

  • value (String, Symbol)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#profile(value = true) ⇒ Chewy::Search::Request

Replaces the value of the profile parameter with the provided value.

Examples:

PlacesIndex.profile
# => <PlacesIndex::Query {..., :body=>{:profile=>true}}>
PlacesIndex.profile.profile(false)
# => <PlacesIndex::Query {:index=>["places"]}>

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end

#query(query_hash) ⇒ Chewy::Search::Request #query { ... } ⇒ Chewy::Search::Request #queryChewy::Search::QueryProxy

Adds query parameter to the search request body.

Overloads:

Returns:

See Also:



261
262
263
264
265
266
267
268
269
# File 'lib/chewy/search/request.rb', line 261

%i[query filter post_filter].each do |name|
  define_method name do |query_hash = UNDEFINED, &block|
    if block || query_hash != UNDEFINED
      modify(name) { must(block || query_hash) }
    else
      Chewy::Search::QueryProxy.new(name, self)
    end
  end
end

#renderHash

ES request body

Returns:

  • (Hash)

    request body



120
121
122
# File 'lib/chewy/search/request.rb', line 120

def render
  @render ||= parameters.render
end

#reorder(*values) ⇒ Chewy::Search::Request

Replaces the value of the sort parameter with the provided value.

Examples:

PlacesIndex.order(:name, population: {order: :asc}).reorder(:coordinates)
# => <PlacesIndex::Query {..., :body=>{:sort=>["coordinates"]}}>

Parameters:

  • values (Array<Hash, String, Symbol>)

    sort fields and options

Returns:

See Also:



322
323
324
# File 'lib/chewy/search/request.rb', line 322

def reorder(value, *values)
  modify(:order) { replace!([value, *values]) }
end

#request_cache(value) ⇒ Chewy::Search::Request

Replaces the value of the request_cache parameter with the provided value. Unlike other boolean fields, the value have to be specified explicitly since it overrides the index-level setting.

Examples:

PlacesIndex.request_cache(true)
# => <PlacesIndex::Query {..., :body=>{:request_cache=>true}}>
PlacesIndex.request_cache(false)
# => <PlacesIndex::Query {..., :body=>{:request_cache=>false}}>

Parameters:

  • value (true, false, nil)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#rescore(value) ⇒ Chewy::Search::Request

Add a rescore part to the request. Further call values are added to the storage array.

Examples:

PlacesIndex.rescore(window_size: 100, query: {}).rescore(window_size: 200, query: {})
# => <PlacesIndex::Query {..., :body=>{:rescore=>[{:window_size=>100, :query=>{}}, {:window_size=>200, :query=>{}}]}}>

Parameters:

  • value (Hash, Array<Hash>)

Returns:

See Also:



637
638
639
640
641
# File 'lib/chewy/search/request.rb', line 637

%i[script_fields indices_boost rescore highlight].each do |name|
  define_method name do |value|
    modify(name) { update!(value) }
  end
end

#responseChewy::Search::Response

Access to ES response wrappers providing useful methods such as Chewy::Search::Response#total or Chewy::Search::Response#max_score.

Returns:

See Also:



104
105
106
# File 'lib/chewy/search/request.rb', line 104

def response
  @response ||= build_response(perform)
end

#response=(from_elasticsearch) ⇒ Object

Wraps and sets the raw Elasticsearch response to provide access to convenience methods.

Parameters:

  • from_elasticsearch (Hash)

    An Elasticsearch response

See Also:



113
114
115
# File 'lib/chewy/search/request.rb', line 113

def response=(from_elasticsearch)
  @response = build_response(from_elasticsearch)
end

#script_fields(value) ⇒ Chewy::Search::Request

Add a script_fields part to the request. Further call values are merged to the storage hash.

Examples:

PlacesIndex
  .script_fields(field1: {script: {lang: 'painless', inline: 'some script here'}})
  .script_fields(field2: {script: {lang: 'painless', inline: 'some script here'}})
# => <PlacesIndex::Query {..., :body=>{:script_fields=>{
#      "field1"=>{:script=>{:lang=>"painless", :inline=>"some script here"}},
#      "field2"=>{:script=>{:lang=>"painless", :inline=>"some script here"}}}}}>

Parameters:

  • value (Hash)

Returns:

See Also:



637
638
639
640
641
# File 'lib/chewy/search/request.rb', line 637

%i[script_fields indices_boost rescore highlight].each do |name|
  define_method name do |value|
    modify(name) { update!(value) }
  end
end

#search_after(*values) ⇒ Chewy::Search::Request

Replaces the storage value for search_after request part.

Examples:

PlacesIndex.search_after(42, 'Moscow').search_after('London')
# => <PlacesIndex::Query {..., :body=>{:search_after=>["London"]}}>

Parameters:

  • value (Array, Object)

Returns:

See Also:



562
563
564
# File 'lib/chewy/search/request.rb', line 562

def search_after(value, *values)
  modify(:search_after) { replace!(values.empty? ? value : [value, *values]) }
end

#search_type(value) ⇒ Chewy::Search::Request

Replaces the value of the search_type request part.

Examples:

PlacesIndex.search_type(:dfs_query_then_fetch)
# => <PlacesIndex::Query {..., :body=>{:search_type=>"dfs_query_then_fetch"}}>

Parameters:

  • value (String, Symbol)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#source(*values) ⇒ Chewy::Search::Request

Updates _source request part. Accepts either an array of field names/templates or a hash with includes and excludes keys. Source also can be disabled entirely or enabled again.

Examples:

PlacesIndex.source(:name).source(includes: [:popularity], excludes: :description)
# => <PlacesIndex::Query {..., :body=>{:_source=>{:includes=>["name", "popularity"], :excludes=>["description"]}}}>
PlacesIndex.source(false)
# => <PlacesIndex::Query {..., :body=>{:_source=>false}}>

Parameters:

  • values (true, false, {Symbol => Array<String, Symbol>, String, Symbol}, Array<String, Symbol>, String, Symbol)

Returns:

See Also:



546
547
548
549
550
# File 'lib/chewy/search/request.rb', line 546

%i[source stored_fields].each do |name|
  define_method name do |value, *values|
    modify(name) { update!(values.empty? ? value : [value, *values]) }
  end
end

#stored_fields(*values) ⇒ Chewy::Search::Request

Updates stored_fields request part. Accepts an array of field names. Can be entirely disabled and enabled back.

Examples:

PlacesIndex.stored_fields(:name).stored_fields(:description)
# => <PlacesIndex::Query {..., :body=>{:stored_fields=>["name", "description"]}}>
PlacesIndex.stored_fields(false)
# => <PlacesIndex::Query {..., :body=>{:stored_fields=>"_none_"}}>

Parameters:

  • values (true, false, String, Symbol, Array<String, Symbol>)

Returns:

See Also:



546
547
548
549
550
# File 'lib/chewy/search/request.rb', line 546

%i[source stored_fields].each do |name|
  define_method name do |value, *values|
    modify(name) { update!(values.empty? ? value : [value, *values]) }
  end
end

#suggest(value) ⇒ Chewy::Search::Request #suggestHash

A dual-purpose method.

Overloads:



669
670
671
672
673
674
675
# File 'lib/chewy/search/request.rb', line 669

def suggest(value = UNDEFINED)
  if value == UNDEFINED
    response.suggest
  else
    modify(:suggest) { update!(value) }
  end
end

#terminate_after(value) ⇒ Chewy::Search::Request

Replaces the value of the terminate_after request part.

Examples:

PlacesIndex.terminate_after(10)
<PlacesIndex::Query {..., :body=>{:terminate_after=>10}}>

Parameters:

  • value (String, Integer)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#timeout(value) ⇒ Chewy::Search::Request

Replaces the value of the timeout request part.

Examples:

PlacesIndex.timeout('1m')
<PlacesIndex::Query {..., :body=>{:timeout=>"1m"}}>

Parameters:

  • value (String, Symbol)

Returns:

See Also:



512
513
514
515
516
# File 'lib/chewy/search/request.rb', line 512

%i[request_cache search_type preference timeout limit offset terminate_after min_score ignore_unavailable].each do |name|
  define_method name do |value|
    modify(name) { replace!(value) }
  end
end

#track_scores(value = true) ⇒ Chewy::Search::Request

Replaces the value of the track_scores parameter with the provided value.

Examples:

PlacesIndex.track_scores
# => <PlacesIndex::Query {..., :body=>{:track_scores=>true}}>
PlacesIndex.track_scores.track_scores(false)
# => <PlacesIndex::Query {:index=>["places"]}>

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end

#track_total_hits(value = true) ⇒ Chewy::Search::Request

Replaces the value of the track_total_hits parameter with the provided value.

Examples:

PlacesIndex.track_total_hits
# => <PlacesIndex::Query {..., :body=>{:track_total_hits=>true}}>
PlacesIndex.track_total_hits.track_total_hits(false)
# => <PlacesIndex::Query {:index=>["places"]}>

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end

#version(value = true) ⇒ Chewy::Search::Request

Replaces the value of the version parameter with the provided value.

Examples:

PlacesIndex.version
# => <PlacesIndex::Query {..., :body=>{:version=>true}}>
PlacesIndex.version.version(false)
# => <PlacesIndex::Query {:index=>["places"]}>

Parameters:

  • value (true, false) (defaults to: true)

Returns:

See Also:



404
405
406
407
408
# File 'lib/chewy/search/request.rb', line 404

%i[track_scores track_total_hits explain version profile none].each do |name|
  define_method name do |value = true|
    modify(name) { replace!(value) }
  end
end