Abort a running benchmark
@example
client.abort_benchmark name: 'my_benchmark'
@option arguments [String] :name A benchmark name
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html
# File lib/elasticsearch/api/actions/abort_benchmark.rb, line 15 def abort_benchmark(arguments={}) valid_params = [ ] method = HTTP_POST path = "_bench/abort/#{arguments[:name]}" params = {} body = nil perform_request(method, path, params, body).body end
Run a single query, or a set of queries, and return statistics on their performance
@example Return statistics for a single query
client.benchmark body: { name: 'my_benchmark', competitors: [ { name: 'query_1', requests: [ { query: { match: { _all: 'a*' } } } ] } ] }
@example Return statistics for a set of “competing” queries
client.benchmark body: { name: 'my_benchmark', competitors: [ { name: 'query_a', requests: [ { query: { match: { _all: 'a*' } } } ] }, { name: 'query_b', requests: [ { query: { match: { _all: 'b*' } } } ] } ] }
@option arguments [List] :index A comma-separated list of index names; use `_all` or empty string
to perform the operation on all indices
@option arguments [String] :type The name of the document type @option arguments [Hash] :body The search definition using the Query DSL @option arguments [Boolean] :verbose Specify whether to return verbose statistics about each iteration
(default: false)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html
# File lib/elasticsearch/api/actions/benchmark.rb, line 50 def benchmark(arguments={}) valid_params = [ :verbose ] method = HTTP_PUT path = "_bench" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Perform multiple index, delete or update operations in a single request.
Pass the operations in the `:body` option as an array of hashes, following Elasticsearch conventions. For operations which take data, pass them as the `:data` option in the operation hash.
@example Perform three operations in a single request, passing actions and data as an array of hashes
client.bulk body: [ { index: { _index: 'myindex', _type: 'mytype', _id: 1 } }, { title: 'foo' }, { index: { _index: 'myindex', _type: 'mytype', _id: 2 } }, { title: 'foo' }, { delete: { _index: 'myindex', _type: 'mytype', _id: 3 } } ]
@example Perform three operations in a single request, passing data in the `:data` option
client.bulk body: [ { index: { _index: 'myindex', _type: 'mytype', _id: 1, data: { title: 'foo' } } }, { update: { _index: 'myindex', _type: 'mytype', _id: 2, data: { doc: { title: 'foo' } } } }, { delete: { _index: 'myindex', _type: 'mytype', _id: 3 } } ]
@example Perform a script-based bulk update, passing scripts in the `:data` option
client.bulk body: [ { update: { _index: 'myindex', _type: 'mytype', _id: 1, data: { script: "ctx._source.counter += value", lang: 'js', params: { value: 1 }, upsert: { counter: 0 } } }}, { update: { _index: 'myindex', _type: 'mytype', _id: 2, data: { script: "ctx._source.counter += value", lang: 'js', params: { value: 42 }, upsert: { counter: 0 } } }} ]
@option arguments [String] :index Default index for items which don't provide one @option arguments [String] :type Default document type for items which don't provide one @option arguments [Array<Hash>] :body An array of operations to perform, each operation is a Hash @option arguments [String] :consistency Explicit write consistency setting for the operation
(options: one, quorum, all)
@option arguments [Boolean] :refresh Refresh the index after performing the operation @option arguments [String] :replication Explicitely set the replication type (options: sync, async) @option arguments [Time] :timeout Explicit operation timeout
@return [Hash] Deserialized Elasticsearch response
@see elasticsearch.org/guide/reference/api/bulk/
# File lib/elasticsearch/api/actions/bulk.rb, line 60 def bulk(arguments={}) valid_params = [ :consistency, :refresh, :replication, :type, :timeout ] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_bulk' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] if body.is_a? Array payload = Utils.__bulkify(body) else payload = body end perform_request(method, path, params, payload).body end
Abort a particular scroll search and clear all the resources associated with it.
@option arguments [List] :scroll_id A comma-separated list of scroll IDs to clear;
use `_all` clear all scroll search contexts
# File lib/elasticsearch/api/actions/clear_scroll.rb, line 12 def clear_scroll(arguments={}) raise ArgumentError, "Required argument 'scroll_id' missing" unless arguments[:scroll_id] scroll_id = arguments.delete(:scroll_id) scroll_ids = case scroll_id when Array scroll_id.join(',') else scroll_id end method = HTTP_DELETE path = Utils.__pathify '_search/scroll' params = {} body = scroll_ids perform_request(method, path, params, body).body end
Get the number of documents for the cluster, index, type, or a query.
@example Get the number of all documents in the cluster
client.count
@example Get the number of documents in a specified index
client.count index: 'myindex'
@example Get the number of documents matching a specific query
index: 'my_index', body: { filtered: { filter: { terms: { foo: ['bar'] } } } }
@option arguments [List] :index A comma-separated list of indices to restrict the results @option arguments [List] :type A comma-separated list of types to restrict the results @option arguments [Hash] :body A query to restrict the results (optional) @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore
`missing` ones (options: none, missing) @until 1.0
@option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing, closed, etc)
@option arguments [Number] :min_score Include only documents with a specific `_score` value in the result @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :routing Specific routing value @option arguments [String] :source The URL-encoded query definition (instead of using the request body)
@see elasticsearch.org/guide/reference/api/count/
# File lib/elasticsearch/api/actions/count.rb, line 37 def count(arguments={}) valid_params = [ :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :min_score, :preference, :routing, :source ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_count' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Return the number of queries matching a document.
Percolator allows you to register queries and then evaluate a document against them: the number of matching queries is returned in the response.
@example Register query named “alert-1” for the “my-index” index
client.index index: 'my-index', type: '.percolator', id: 'alert-1', body: { query: { query_string: { query: 'foo' } } }
@example Return the number of matching queries for a custom document
client.count_percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo Bar" } } # => { ..., total: 1}
@example Return the number of matching queries for an existing document
client.index index: 'my-index', type: 'my-type', id: '123', body: { title: "Foo Bar" } client.count_percolate index: 'my-index', type: 'my-type', id: '123' # => { ..., total: 1}
@option arguments [String] :index The index of the document being percolated. (Required) @option arguments [String] :type The type of the document being percolated. (Required) @option arguments [String] :id Fetch the document specified by index/type/id and
use it instead of the passed `doc`
@option arguments [Hash] :body The percolator request definition using the percolate DSL @option arguments [List] :routing A comma-separated list of specific routing values @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing or closed)
@option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are
open, closed or both. (options: open, closed)
@option arguments [String] :percolate_index The index to percolate the document into. Defaults to passed `index`. @option arguments [String] :percolate_type The type to percolate document into. Defaults to passed `type`. @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-percolate.html
# File lib/elasticsearch/api/actions/count_percolate.rb, line 51 def count_percolate(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :version, :version_type ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], '_percolate/count' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Create a document.
Enforce the create operation when indexing a document – the operation will return an error when the document already exists.
@example Create a document
client.create index: 'myindex', type: 'mytype', id: '1', body: { title: 'Test 1', tags: ['y', 'z'], published: true, published_at: Time.now.utc.iso8601, counter: 1 }
@option (see #index)
(The `:op_type` argument is ignored.)
@see elasticsearch.org/guide/reference/api/index_/
# File lib/elasticsearch/api/actions/create.rb, line 29 def create(arguments={}) index arguments.update :op_type => 'create' end
Delete a single document.
@example Delete a document
client.delete index: 'myindex', type: 'mytype', id: '1'
@example Delete a document with specific routing
client.delete index: 'myindex', type: 'mytype', id: '1', routing: 'abc123'
@option arguments [String] :id The document ID (Required) @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (Required) @option arguments [String] :consistency Specific write consistency setting for the operation
(options: one, quorum, all)
@option arguments [String] :parent ID of parent document @option arguments [Boolean] :refresh Refresh the index after performing the operation @option arguments [String] :replication Specific replication type (options: sync, async) @option arguments [String] :routing Specific routing value @option arguments [Time] :timeout Explicit operation timeout @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force)
@see elasticsearch.org/guide/reference/api/delete/
# File lib/elasticsearch/api/actions/delete.rb, line 31 def delete(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :consistency, :parent, :refresh, :replication, :routing, :timeout, :version, :version_type ] method = HTTP_DELETE path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body rescue Exception => e # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false else raise(e) end end
Delete documents which match specified query.
Provide the query either as a “query string” query in the `:q` argument, or using the Elasticsearch's [Query DSL](www.elasticsearch.org/guide/reference/query-dsl/) in the `:body` argument.
@example Deleting documents with a simple query
client.delete_by_query index: 'myindex', q: 'title:test'
@example Deleting documents using the Query DSL
client.delete_by_query index: 'myindex', body: { query: { term: { published: false } } }
@option arguments [List] :index A comma-separated list of indices to restrict the operation;
use `_all`to perform the operation on all indices (*Required*)
@option arguments [List] :type A comma-separated list of types to restrict the operation @option arguments [Hash] :body A query to restrict the operation @option arguments [String] :analyzer The analyzer to use for the query string @option arguments [String] :consistency Specific write consistency setting for the operation
(options: one, quorum, all)
@option arguments [String] :default_operator The default operator for query string query (AND or OR)
(options: AND, OR)
@option arguments [String] :df The field to use as default where no field prefix is given in the query string @option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that
are open, closed or both. (options: open, closed)
@option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore
`missing` ones (options: none, missing) @until 1.0
@option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing, closed, etc)
@option arguments [String] :replication Specific replication type (options: sync, async) @option arguments [String] :q Query in the Lucene query string syntax @option arguments [String] :routing Specific routing value @option arguments [String] :source The URL-encoded query definition (instead of using the request body) @option arguments [Time] :timeout Explicit operation timeout
@see www.elasticsearch.org/guide/reference/api/delete-by-query/
# File lib/elasticsearch/api/actions/delete_by_query.rb, line 45 def delete_by_query(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] valid_params = [ :analyzer, :consistency, :default_operator, :df, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :replication, :q, :routing, :source, :timeout ] method = HTTP_DELETE path = Utils.__pathify Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '/_query' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Remove an indexed script from Elasticsearch
@option arguments [String] :id Script ID (Required) @option arguments [String] :lang Script language (Required) @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/modules-scripting.html
# File lib/elasticsearch/api/actions/delete_script.rb, line 14 def delete_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] valid_params = [ :version, :version_type ] method = HTTP_DELETE path = "_scripts/#{arguments.delete(:lang)}/#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end
Retrieve an indexed template from Elasticsearch
@option arguments [String] :id Template ID
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html
# File lib/elasticsearch/api/actions/delete_template.rb, line 11 def delete_template(arguments={}) method = HTTP_DELETE path = "_search/template/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end
Return true if the specified document exists, false otherwise.
@example
client.exists index: 'myindex', type: 'mytype', id: '1'
@option arguments [String] :id The document ID (Required) @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (default: `_all`) @option arguments [String] :parent The ID of the parent document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation @option arguments [String] :routing Specific routing value
@see elasticsearch.org/guide/reference/api/get/
# File lib/elasticsearch/api/actions/exists.rb, line 23 def exists(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] arguments[:type] ||= UNDERSCORE_ALL valid_params = [ :parent, :preference, :realtime, :refresh, :routing ] method = HTTP_HEAD path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).status == 200 ? true : false rescue Exception => e if e.class.to_s =~ /NotFound/ || e.message =~ /Not\s*Found|404/ false else raise e end end
Return information if and how well a document matches a query.
The returned information contains a `_score` and its explanation, if the document matches the query.
@example Passing the query in the Lucene query syntax as the `:q` URL parameter
client.explain index: 'myindex', type: 'mytype', id: '1', q: 'test'
@example Passing the query in the Query DSL as the request `:body`
client.explain index: 'myindex', type: 'mytype', id: '1', body: { query: { match: { title: 'test' } } }
@option arguments [String] :id The document ID (Required) @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (Required) @option arguments [Hash] :body The query definition using the Query DSL (Required) @option arguments [Boolean] :analyze_wildcard Specify whether wildcards and prefix queries in the query string
query should be analyzed (default: false)
@option arguments [String] :analyzer The analyzer for the query string query @option arguments [String] :default_operator The default operator for query string query (AND or OR)
(options: AND, OR)
@option arguments [String] :df The default field for query string query (default: _all) @option arguments [List] :fields A comma-separated list of fields to return in the response @option arguments [Boolean] :lenient Specify whether format-based query failures
(such as providing text to a numeric field) should be ignored
@option arguments [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased @option arguments [String] :parent The ID of the parent document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :q Query in the Lucene query string syntax @option arguments [String] :routing Specific routing value @option arguments [String] :source The URL-encoded query definition (instead of using the request body) @option arguments [String] :_source Specify whether the _source field should be returned,
or a list of fields to return
@option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field @option arguments [String] :_source_include A list of fields to extract and return from the _source field
@see elasticsearch.org/guide/reference/api/explain/
# File lib/elasticsearch/api/actions/explain.rb, line 45 def explain(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :analyze_wildcard, :analyzer, :default_operator, :df, :fields, :lenient, :lowercase_expanded_terms, :parent, :preference, :q, :routing, :source, :_source, :_source_include, :_source_exclude ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_explain' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end
Return a specified document.
The response contains full document, as stored in Elasticsearch, incl. `_source`, `_version`, etc.
@example Get a document
client.get index: 'myindex', type: 'mytype', id: '1'
@option arguments [String] :id The document ID (Required) @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document; use `_all` to fetch the first document
matching the ID across all types) (*Required*)
@option arguments [List] :fields A comma-separated list of fields to return in the response @option arguments [String] :parent The ID of the parent document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation @option arguments [String] :routing Specific routing value @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) @option arguments [String] :_source Specify whether the _source field should be returned,
or a list of fields to return
@option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field @option arguments [String] :_source_include A list of fields to extract and return from the _source field
@see elasticsearch.org/guide/reference/api/get/
# File lib/elasticsearch/api/actions/get.rb, line 34 def get(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] arguments[:type] ||= UNDERSCORE_ALL valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :version, :version_type, :_source, :_source_include, :_source_exclude ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, valid_params body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body rescue Exception => e # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false else raise(e) end end
Retrieve an indexed script from Elasticsearch
@option arguments [String] :id Script ID (Required) @option arguments [String] :lang Script language (Required)
# File lib/elasticsearch/api/actions/get_script.rb, line 12 def get_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] method = HTTP_GET path = "_scripts/#{arguments[:lang]}/#{arguments[:id]}" params = {} body = nil perform_request(method, path, params, body).body end
Return a specified document's `_source`.
The response contains just the original document, as passed to Elasticsearch during indexing.
@example Get a document `_source`
client.get_source index: 'myindex', type: 'mytype', id: '1'
@option arguments [String] :id The document ID (Required) @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document; use `_all` to fetch the first document
matching the ID across all types) (*Required*)
@option arguments [List] :fields A comma-separated list of fields to return in the response @option arguments [String] :parent The ID of the parent document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation @option arguments [String] :routing Specific routing value @option arguments [String] :_source Specify whether the _source field should be returned,
or a list of fields to return
@option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field @option arguments [String] :_source_include A list of fields to extract and return from the _source field
@see elasticsearch.org/guide/reference/api/get/
@since 0.90.1
# File lib/elasticsearch/api/actions/get_source.rb, line 34 def get_source(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] arguments[:type] ||= UNDERSCORE_ALL valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_include, :_source_exclude ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_source' params = Utils.__validate_and_extract_params arguments, valid_params body = nil params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body rescue Exception => e # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false else raise(e) end end
Retrieve an indexed script from Elasticsearch
@option arguments [String] :id Template ID (Required) @option arguments [Hash] :body The document
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html
# File lib/elasticsearch/api/actions/get_template.rb, line 12 def get_template(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] method = HTTP_GET path = "_search/template/#{arguments[:id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end
Create or update a document.
The `index` API will either create a new document, or update an existing one, when a document `:id` is passed. When creating a document, an ID will be auto-generated, when it's not passed as an argument.
You can specifically enforce the create operation by settint the `op_type` argument to `create`, or by using the {Actions#create} method.
Optimistic concurrency control is performed, when the `version` argument is specified. By default, no version checks are performed.
By default, the document will be available for {Actions#get} immediately, for {Actions#search} only after an index refresh operation has been performed (either automatically or manually).
@example Create or update a document `myindex/mytype/1`
client.index index: 'myindex', type: 'mytype', id: '1', body: { title: 'Test 1', tags: ['y', 'z'], published: true, published_at: Time.now.utc.iso8601, counter: 1 }
@example Refresh the index after the operation (useful e.g. in integration tests)
client.index index: 'myindex', type: 'mytype', id: '1', body: { title: 'TEST' }, refresh: true client.search index: 'myindex', q: 'title:test'
@example Create a document with a specific expiration time (TTL)
# Decrease the default housekeeping interval first: client.cluster.put_settings body: { transient: { 'indices.ttl.interval' => '1s' } } # Enable the `_ttl` property for all types within the index client.indices.create index: 'myindex', body: { mappings: { mytype: { _ttl: { enabled: true } } } } client.index index: 'myindex', type: 'mytype', id: '1', body: { title: 'TEST' }, ttl: '5s' sleep 3 and client.get index: 'myindex', type: 'mytype', id: '1' # => {"_index"=>"myindex" ... "_source"=>{"title"=>"TEST"}} sleep 3 and client.get index: 'myindex', type: 'mytype', id: '1' # => Elasticsearch::Transport::Transport::Errors::NotFound: [404] ...
@option arguments [String] :id Document ID (optional, will be auto-generated if missing) @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (Required) @option arguments [Hash] :body The document @option arguments [String] :consistency Explicit write consistency setting for the operation
(options: one, quorum, all)
@option arguments [String] :op_type Explicit operation type (options: index, create) @option arguments [String] :parent ID of the parent document @option arguments [String] :percolate Percolator queries to execute while indexing the document @option arguments [Boolean] :refresh Refresh the index after performing the operation @option arguments [String] :replication Specific replication type (options: sync, async) @option arguments [String] :routing Specific routing value @option arguments [Time] :timeout Explicit operation timeout @option arguments [Time] :timestamp Explicit timestamp for the document @option arguments [Duration] :ttl Expiration time for the document @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force)
@see elasticsearch.org/guide/reference/api/index_/
# File lib/elasticsearch/api/actions/index.rb, line 73 def index(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :consistency, :op_type, :parent, :percolate, :refresh, :replication, :routing, :timeout, :timestamp, :ttl, :version, :version_type ] method = arguments[:id] ? HTTP_PUT : HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Return simple information about the cluster (name, version).
@see elasticsearch.org/guide/
# File lib/elasticsearch/api/actions/info.rb, line 9 def info(arguments={}) method = HTTP_GET path = "" params = {} body = nil perform_request(method, path, params, body).body end
Return a list of running benchmarks
@example
client.list_benchmarks
@option arguments [List] :index A comma-separated list of index names; use `_all` or empty string
to perform the operation on all indices
@option arguments [String] :type The name of the document type
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-benchmark.html
# File lib/elasticsearch/api/actions/list_benchmarks.rb, line 17 def list_benchmarks(arguments={}) valid_params = [ ] method = HTTP_GET path = "_bench" params = {} body = nil perform_request(method, path, params, body).body end
Return multiple documents from one or more indices in a single request.
Pass the request definition in the `:body` argument, either as an Array of `docs` specifications, or `ids`, when the `:index` and document `:type` are specified.
@example Get multiple documents fully specified in the `docs` definition
client.mget body: { docs: [ { _index: 'myindex', _type: 'mytype', _id: '1' }, { _index: 'myindex', _type: 'mytype', _id: '2' }, { _index: 'myindex', _type: 'mytype', _id: '3' } ] }
@example Get multiple documents specified by `ids` while passing `:index` and `:type`
client.mget index: 'myindex', type: 'mytype', body: { ids: ['1', '2', '3'] }
@example Get only specific fields from documents
client.mget index: 'myindex', type: 'mytype', body: { ids: ['1', '2', '3'] }, fields: ['title']
@option arguments [String] :index The name of the index @option arguments [String] :type The type of the document @option arguments [Hash] :body Document identifiers; can be either `docs` (containing full document information)
or `ids` (when index and type is provided in the URL (*Required*)
@option arguments [List] :fields A comma-separated list of fields to return in the response @option arguments [String] :parent The ID of the parent document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :realtime Specify whether to perform the operation in realtime or search mode @option arguments [Boolean] :refresh Refresh the shard containing the document before performing the operation @option arguments [String] :routing Specific routing value @option arguments [String] :_source Specify whether the _source field should be returned,
or a list of fields to return
@option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field @option arguments [String] :_source_include A list of fields to extract and return from the _source field
@see elasticsearch.org/guide/reference/api/multi-get/
# File lib/elasticsearch/api/actions/mget.rb, line 46 def mget(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :fields, :parent, :preference, :realtime, :refresh, :routing, :_source, :_source_include, :_source_exclude ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_mget' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end
Return documents similar to the specified one.
Performs a `more_like_this` query with the specified document as the input.
@example Search for similar documents using the `title` property of document `myindex/mytype/1`
# First, let's setup a synonym-aware analyzer ("quick" <=> "fast") client.indices.create index: 'myindex', body: { settings: { analysis: { filter: { synonyms: { type: 'synonym', synonyms: [ "quick,fast" ] } }, analyzer: { title_synonym: { type: 'custom', tokenizer: 'whitespace', filter: ['lowercase', 'stop', 'snowball', 'synonyms'] } } } }, mappings: { mytype: { properties: { title: { type: 'string', analyzer: 'title_synonym' } } } } } # Index three documents client.index index: 'myindex', type: 'mytype', id: 1, body: { title: 'Quick Brown Fox' } client.index index: 'myindex', type: 'mytype', id: 2, body: { title: 'Slow Black Dog' } client.index index: 'myindex', type: 'mytype', id: 3, body: { title: 'Fast White Rabbit' } client.indices.refresh index: 'myindex' client.mlt index: 'myindex', type: 'mytype', id: 1, mlt_fields: 'title', min_doc_freq: 1, min_term_freq: 1 # => { ... {"title"=>"Fast White Rabbit"}}]}}
@option arguments [String] :id The document ID (Required) @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (use `_all` to fetch
the first document matching the ID across all types) (*Required*)
@option arguments [Hash] :body A specific search request definition @option arguments [Number] :boost_terms The boost factor @option arguments [Number] :max_doc_freq The word occurrence frequency as count: words with higher occurrence
in the corpus will be ignored
@option arguments [Number] :max_query_terms The maximum query terms to be included in the generated query @option arguments [Number] :max_word_len The minimum length of the word: longer words will be ignored @option arguments [Number] :min_doc_freq The word occurrence frequency as count: words with lower occurrence
in the corpus will be ignored
@option arguments [Number] :min_term_freq The term frequency as percent: terms with lower occurence
in the source document will be ignored
@option arguments [Number] :min_word_len The minimum length of the word: shorter words will be ignored @option arguments [List] :mlt_fields Specific fields to perform the query against @option arguments [Number] :percent_terms_to_match How many terms have to match in order to consider
the document a match (default: 0.3)
@option arguments [String] :routing Specific routing value @option arguments [Number] :search_from The offset from which to return results @option arguments [List] :search_indices A comma-separated list of indices to perform the query against
(default: the index containing the document)
@option arguments [String] :search_query_hint The search query hint @option arguments [String] :search_scroll A scroll search request definition @option arguments [Number] :search_size The number of documents to return (default: 10) @option arguments [String] :search_source A specific search request definition (instead of using the request body) @option arguments [String] :search_type Specific search type (eg. `dfs_then_fetch`, `count`, etc) @option arguments [List] :search_types A comma-separated list of types to perform the query against
(default: the same type as the document)
@option arguments [List] :stop_words A list of stop words to be ignored
@see elasticsearch.org/guide/reference/api/more-like-this/
# File lib/elasticsearch/api/actions/mlt.rb, line 84 def mlt(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :boost_terms, :max_doc_freq, :max_query_terms, :max_word_len, :min_doc_freq, :min_term_freq, :min_word_len, :mlt_fields, :percent_terms_to_match, :routing, :search_from, :search_indices, :search_query_hint, :search_scroll, :search_size, :search_source, :search_type, :search_types, :stop_words ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_mlt' params = Utils.__validate_and_extract_params arguments, valid_params [:mlt_fields, :search_indices, :search_types, :stop_words].each do |name| params[name] = Utils.__listify(params[name]) if params[name] end body = arguments[:body] perform_request(method, path, params, body).body end
Perform multiple percolate operations in a single request, similar to the {#msearch} API
Pass the percolate definitions as header-body pairs in the `:body` argument, as an Array of Hashes.
@example Perform two different percolations in a single request
client.mpercolate \ body: [ { percolate: { index: "my-index", type: "my-type" } }, { doc: { message: "foo bar" } }, { percolate: { index: "my-other-index", type: "my-other-type", id: "1" } }, { } ]
@option arguments [String] :index The index of the document being count percolated to use as default @option arguments [String] :type The type of the document being percolated to use as default. @option arguments [Array<Hash>] The percolate request definitions (header & body pairs) (Required) @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing or closed)
@option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are
open, closed or both. (options: open, closed)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-percolate.html
# File lib/elasticsearch/api/actions/mpercolate.rb, line 32 def mpercolate(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = "_mpercolate" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] case when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : MultiJson.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload).body end
Perform multiple search operations in a single request.
Pass the search definitions in the `:body` argument
@example Perform multiple different searches as `:search`
client.msearch \ body: [ { search: { query: { match_all: {} } } }, { index: 'myindex', type: 'mytype', search: { query: { query_string: { query: '"Test 1"' } } } }, { search_type: 'count', search: { facets: { published: { terms: { field: 'published' } } } } } ]
@example Perform multiple different searches as an array of meta/data pairs
client.msearch \ body: [ { query: { match_all: {} } }, { index: 'myindex', type: 'mytype' }, { query: { query_string: { query: '"Test 1"' } } }, { search_type: 'count' }, { facets: { published: { terms: { field: 'published' } } } } ]
@option arguments [List] :index A comma-separated list of index names to use as default @option arguments [List] :type A comma-separated list of document types to use as default @option arguments [Array<Hash>] :body An array of request definitions, each definition is a Hash;
pass the search definition as a `:search` argument
@option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch,
dfs_query_then_fetch, dfs_query_and_fetch, count, scan)
@see www.elasticsearch.org/guide/reference/api/multi-search/
# File lib/elasticsearch/api/actions/msearch.rb, line 38 def msearch(arguments={}) raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :search_type ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_msearch' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] case when body.is_a?(Array) && body.any? { |d| d.has_key? :search } payload = body. inject([]) do |sum, item| meta = item data = meta.delete(:search) sum << meta sum << data sum end. map { |item| MultiJson.dump(item) } payload << "" unless payload.empty? payload = payload.join("\n") when body.is_a?(Array) payload = body.map { |d| d.is_a?(String) ? d : MultiJson.dump(d) } payload << "" unless payload.empty? payload = payload.join("\n") else payload = body end perform_request(method, path, params, payload).body end
Returns information and statistics about terms in the fields of multiple documents in a single request/response. The semantics are similar to the {#mget} API.
@example Return information about multiple documents in a specific index
subject.mtermvectors index: 'my-index', type: 'my-type', body: { ids: [1, 2, 3] }
@option arguments [String] :index The name of the index @option arguments [String] :type The type of the document @option arguments [Hash] :body Document identifiers; can be either `docs` (containing full document information)
or `ids` (when index and type is provided in the URL (*Required*)
@option arguments [List] :ids A comma-separated list of documents ids (alternative to `:body`) @option arguments [Boolean] :term_statistics Whether total term frequency and
document frequency should be returned.
@option arguments [Boolean] :field_statistics Whether document count, sum of document frequencies
and sum of total term frequencies should be returned.
@option arguments [List] :fields A comma-separated list of fields to return @option arguments [Boolean] :offsets Whether term offsets should be returned @option arguments [Boolean] :positions Whether term positions should be returned @option arguments [Boolean] :payloads Whether term payloads should be returned @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :realtime Specifies if requests are real-time as opposed to near-real-time
(default: true)
@option arguments [String] :routing Specific routing value @option arguments [String] :parent Parent ID of documents
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/docs-multi-termvectors.html
@see mget @see termvector
# File lib/elasticsearch/api/actions/mtermvectors.rb, line 37 def mtermvectors(arguments={}) valid_params = [ :ids, :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :realtime, :routing, :parent ] ids = arguments.delete(:ids) method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), '_mtermvectors' params = Utils.__validate_and_extract_params arguments, valid_params if ids body = { :ids => ids } else body = arguments[:body] end perform_request(method, path, params, body).body end
Return names of queries matching a document.
Percolator allows you to register queries and then evaluate a document against them: the IDs of matching queries are returned in the response.
@example Register queries named “alert-1” and “alert-2” for the “my-index” index
client.index index: 'my-index', type: '.percolator', id: 'alert-1', body: { query: { query_string: { query: 'foo' } } } client.index index: 'my-index', type: '.percolator', id: 'alert-2', body: { query: { query_string: { query: 'bar' } } }
@example Evaluate a custom document (passed as `:doc`) against the queries
client.percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo" } } # => {..., matches: [ {_index: 'my-index', _id: 'alert-1'} ]} client.percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo Bar" } } # => {..., matches: [ {_index: 'my-index', _id: 'alert-2'}, {_index: 'my-index', _id: 'alert-1'} ] }
@example Evaluate an existing document against the queries
client.index index: 'my-index', type: 'my-type', id: 123, body: { title: "Foo Bar" } client.percolate index: 'my-index', type: 'my-type', id: '123' # => { ..., matches: [ {_index: 'my-index', _id: 'alert-2'}, { _index: 'my-index', _id: 'alert-1'} ] }
@example Register a query with custom `priority` property
client.index index: 'my-index', type: '.percolator', id: 'alert-high-1', body: { query: { query_string: { query: 'foo' } }, priority: 'high' }
@example Evaluate a document against “high priority” percolator queries
client.percolate index: 'my-index', type: 'my-type', body: { doc: { title: "Foo" }, filter: { term: { priority: 'high' } } } # => {..., matches: [ {_index: 'my-index', _id: 'alert-high-1'} ]}
@option arguments [String] :index The index of the document being percolated. (Required) @option arguments [String] :type The type of the document being percolated. (Required) @option arguments [String] :id Fetch the document specified by index/type/id and
use it instead of the passed `doc`
@option arguments [Hash] :body The percolator request definition using the percolate DSL @option arguments [List] :routing A comma-separated list of specific routing values @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing or closed)
@option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices that are
open, closed or both. (options: open, closed)
@option arguments [String] :percolate_index The index to percolate the document into. Defaults to passed `index`. @option arguments [String] :percolate_format Return an array of matching query IDs instead of objects.
(options: ids)
@option arguments [String] :percolate_type The type to percolate document into. Defaults to passed `type`. @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-percolate.html
# File lib/elasticsearch/api/actions/percolate.rb, line 77 def percolate(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :routing, :preference, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :percolate_index, :percolate_type, :percolate_format, :version, :version_type ] method = HTTP_GET path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], '_percolate' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Returns true if the cluster returns a sucessfull HTTP response, false otherwise.
@example
client.ping
@see elasticsearch.org/guide/
# File lib/elasticsearch/api/actions/ping.rb, line 13 def ping(arguments={}) method = HTTP_HEAD path = "" params = {} body = nil perform_request(method, path, params, body).status == 200 ? true : false rescue Exception => e if e.class.to_s =~ /NotFound/ || e.message =~ /Not\s*Found|404/ false else raise e end end
Store a script in an internal index (`.scripts`), to be able to reference them in search definitions (with dynamic scripting disabled)
@example Storing an Mvel script in Elasticsearch and using it in function score
client.put_script lang: 'groovy', id: 'my_score', body: { script: 'log(_score * factor)' } client.search body: { query: { function_score: { query: { match: { title: 'foo' } }, functions: [ { script_score: { script_id: 'my_score', params: { factor: 3 } } } ] } } }
@option arguments [String] :id Script ID (Required) @option arguments [String] :lang Script language (Required) @option arguments [Hash] :body A JSON document containing the script (Required) @option arguments [Number] :version Explicit version number for concurrency control @option arguments [String] :version_type Specific version type (options: internal, external, external_gte, force) @option arguments [String] :op_type Explicit operation type (options: index, create)
# File lib/elasticsearch/api/actions/put_script.rb, line 30 def put_script(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'lang' missing" unless arguments[:lang] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] valid_params = [ :op_type, :version, :version_type ] method = HTTP_PUT path = "_scripts/#{arguments.delete(:lang)}/#{arguments[:id]}" params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Store a template for the search definition in Elasticsearch, to be later used with the `search_template` method
@option arguments [String] :id Template ID (Required) @option arguments [Hash] :body The document (Required)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-template.html
# File lib/elasticsearch/api/actions/put_template.rb, line 13 def put_template(arguments={}) raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] raise ArgumentError, "Required argument 'body' missing" unless arguments[:body] method = HTTP_PUT path = "_search/template/#{arguments[:id]}" params = {} body = arguments[:body] perform_request(method, path, params, body).body end
Efficiently iterate over a large result set.
When using `from` and `size` to return a large result sets, performance drops as you “paginate” in the set, and you can't guarantee the consistency when the index is being updated at the same time.
“Scrolling” the results is frequently used with the `scan` search type.
@example A basic example
result = client.search index: 'scrollindex', scroll: '5m', body: { query: { match: { title: 'test' } }, sort: '_id' } result = client.scroll scroll: '5m', scroll_id: result['_scroll_id']
@example Call the `scroll` API until all the documents are returned
# Index 1,000 documents client.indices.delete index: 'test' 1_000.times do |i| client.index index: 'test', type: 'test', id: i+1, body: {title: "Test #{i}"} end client.indices.refresh index: 'test' # Open the "view" of the index with the `scan` search_type r = client.search index: 'test', search_type: 'scan', scroll: '5m', size: 10 # Call the `scroll` API until empty results are returned while r = client.scroll(scroll_id: r['_scroll_id'], scroll: '5m') and not r['hits']['hits'].empty? do puts "--- BATCH #{defined?($i) ? $i += 1 : $i = 1} -------------------------------------------------" puts r['hits']['hits'].map { |d| d['_source']['title'] }.inspect puts end
@option arguments [String] :scroll_id The scroll ID @option arguments [Hash] :body The scroll ID if not passed by URL or query parameter. @option arguments [Duration] :scroll Specify how long a consistent view of the index
should be maintained for scrolled search
@see www.elasticsearch.org/guide/en/elasticsearch/guide/current/scan-scroll.html#scan-scroll @see www.elasticsearch.org/guide/reference/api/search/scroll/ @see www.elasticsearch.org/guide/reference/api/search/search-type/
# File lib/elasticsearch/api/actions/scroll.rb, line 46 def scroll(arguments={}) method = HTTP_GET path = "_search/scroll" valid_params = [ :scroll, :scroll_id ] params = Utils.__validate_and_extract_params arguments, valid_params body = params.delete(:scroll_id) || arguments[:body] perform_request(method, path, params, body).body end
Return documents matching a query, as well as aggregations (facets), highlighted snippets, suggestions, etc.
The search API is used to query one or more indices either using simple [query string queries](www.elasticsearch.org/guide/reference/api/search/uri-request/) as the `:q` argument , or by passing the [full request definition](www.elasticsearch.org/guide/reference/api/search/request-body/) in the [Query DSL](www.elasticsearch.org/guide/reference/query-dsl/) as the `:body` argument.
@example Search with a simple query string query
client.search index: 'myindex', q: 'title:test'
@example Passing a full request definition in the Elasticsearch's Query DSL as a `Hash`
client.search index: 'myindex', body: { query: { match: { title: 'test' } }, facets: { tags: { terms: { field: 'tags' } } } }
@example Paginating results: return 10 documents, beginning from the 10th
client.search index: 'myindex', body: { query: { match: { title: 'test' } }, from: 10, size: 10 }
@example Passing the search definition as a `String`, built with a JSON builder
require 'jbuilder' json = Jbuilder.encode do |json| json.query do json.match do json.title do json.query 'test 1' json.operator 'and' end end end end client.search index: 'myindex', body: json
@example Wrapping the result in [`Hashie::Mash`](github.com/intridea/hashie) for easier access
response = client.search index: 'myindex', body: { query: { match: { title: 'test' } }, facets: { tags: { terms: { field: 'tags' } } } } response = Hashie::Mash.new response response.hits.hits.first._source.title response.facets.tags.terms.to_a.map { |f| "#{f.term} [#{f.count}]" }.join(', ')
@option arguments [List] :index A comma-separated list of index names to search; use `_all`
or empty string to perform the operation on all indices
@option arguments [List] :type A comma-separated list of document types to search;
leave empty to perform the operation on all types
@option arguments [Hash] :body The search definition using the Query DSL @option arguments [String] :analyzer The analyzer to use for the query string @option arguments [Boolean] :analyze_wildcard Specify whether wildcard and prefix queries should be analyzed
(default: false)
@option arguments [String] :default_operator The default operator for query string query (AND or OR)
(options: AND, OR)
@option arguments [String] :df The field to use as default where no field prefix is given in the query string @option arguments [Boolean] :explain Specify whether to return detailed information about score computation
as part of a hit
@option arguments [List] :fields A comma-separated list of fields to return as part of a hit @option arguments [Number] :from Starting offset (default: 0) @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore `missing` ones
(options: none, missing)
@option arguments [Boolean] :lenient Specify whether format-based query failures
(such as providing text to a numeric field) should be ignored
@option arguments [Boolean] :lowercase_expanded_terms Specify whether query terms should be lowercased @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :q Query in the Lucene query string syntax @option arguments [List] :routing A comma-separated list of specific routing values @option arguments [Duration] :scroll Specify how long a consistent view of the index should be maintained
for scrolled search
@option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch,
dfs_query_then_fetch, dfs_query_and_fetch, count, scan)
@option arguments [Number] :size Number of hits to return (default: 10) @option arguments [List] :sort A comma-separated list of <field>:<direction> pairs @option arguments [String] :source The URL-encoded request definition using the Query DSL
(instead of using request body)
@option arguments [String] :_source Specify whether the _source field should be returned,
or a list of fields to return
@option arguments [String] :_source_exclude A list of fields to exclude from the returned _source field @option arguments [String] :_source_include A list of fields to extract and return from the _source field @option arguments [List] :stats Specific 'tag' of the request for logging and statistical purposes @option arguments [String] :suggest_field Specify which field to use for suggestions @option arguments [String] :suggest_mode Specify suggest mode (options: missing, popular, always) @option arguments [Number] :suggest_size How many suggestions to return in response @option arguments [Text] :suggest_text The source text for which the suggestions should be returned @option arguments [Time] :timeout Explicit operation timeout @option arguments [Boolean] :version Specify whether to return document version as part of a hit
@return [Hash]
@see www.elasticsearch.org/guide/reference/api/search/ @see www.elasticsearch.org/guide/reference/api/search/request-body/
# File lib/elasticsearch/api/actions/search.rb, line 114 def search(arguments={}) arguments[:index] = UNDERSCORE_ALL if ! arguments[:index] && arguments[:type] valid_params = [ :analyzer, :analyze_wildcard, :default_operator, :df, :explain, :fields, :from, :ignore_indices, :ignore_unavailable, :allow_no_indices, :expand_wildcards, :lenient, :lowercase_expanded_terms, :preference, :q, :query_cache, :routing, :scroll, :search_type, :size, :sort, :source, :_source, :_source_include, :_source_exclude, :stats, :suggest_field, :suggest_mode, :suggest_size, :suggest_text, :timeout, :version ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), UNDERSCORE_SEARCH ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body end
Returns the names of indices and shards on which a search request would be executed
@option arguments [String] :index The name of the index @option arguments [String] :type The type of the document @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :routing Specific routing value @option arguments [Boolean] :local Return local information, do not retrieve the state from master node
(default: false)
@option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored when
unavailable (missing or closed)
@option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves
into no concrete indices. (This includes `_all` or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices
that are open, closed or both. (options: open, closed)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/search-shards.html
# File lib/elasticsearch/api/actions/search_shards.rb, line 24 def search_shards(arguments={}) valid_params = [ :preference, :routing, :local, :ignore_unavailable, :allow_no_indices, :expand_wildcards ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search_shards' ) params = Utils.__validate_and_extract_params arguments, valid_params body = nil perform_request(method, path, params, body).body end
Configure the search definition witha template in Mustache and parameters
@example Insert the start and end values for the `range` query
client.search_template index: 'myindex', body: { template: { query: { range: { date: { gte: "{{start}}", lte: "{{end}}" } } } }, params: { start: "2014-02-01", end: "2014-03-01" } }
@option arguments [List] :index A comma-separated list of index names to search; use `_all` or empty
string to perform the operation on all indices
@option arguments [List] :type A comma-separated list of document types to search;
leave empty to perform the operation on all types
@option arguments [Hash] :body The search definition template and its params @option arguments [Boolean] :ignore_unavailable Whether specified concrete indices should be ignored
when unavailable (missing or closed)
@option arguments [Boolean] :allow_no_indices Whether to ignore if a wildcard indices expression resolves into
no concrete indices. (This includes `_all` string or when no indices have been specified)
@option arguments [String] :expand_wildcards Whether to expand wildcard expression to concrete indices
that are open, closed or both. (options: open, closed)
@option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [List] :routing A comma-separated list of specific routing values @option arguments [Duration] :scroll Specify how long a consistent view of the index should be maintained
for scrolled search
@option arguments [String] :search_type Search operation type (options: query_then_fetch, query_and_fetch,
dfs_query_then_fetch, dfs_query_and_fetch, count, scan)
@see www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-template.html
# File lib/elasticsearch/api/actions/search_template.rb, line 43 def search_template(arguments={}) valid_params = [ :ignore_unavailable, :allow_no_indices, :expand_wildcards, :preference, :routing, :scroll, :search_type ] method = HTTP_GET path = Utils.__pathify( Utils.__listify(arguments[:index]), Utils.__listify(arguments[:type]), '_search/template' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Return query terms suggestions based on provided text and configuration.
Pass the request definition in the `:body` argument.
@example Return query terms suggestions (“auto-correction”)
client.suggest index: 'myindex', body: { my_suggest: { text: 'tset', term: { field: 'title' } } } # => { ... "my_suggest"=>[ {"text"=>"tset", ... "options"=>[{"text"=>"test", "score"=>0.75, "freq"=>5}] }]}
@option arguments [List] :index A comma-separated list of index names to restrict the operation;
use `_all` or empty string to perform the operation on all indices
@option arguments [Hash] :body The request definition @option arguments [String] :ignore_indices When performed on multiple indices, allows to ignore `missing` ones
(options: none, missing)
@option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :routing Specific routing value @option arguments [String] :source The URL-encoded request definition (instead of using request body)
@since 0.90
@see elasticsearch.org/guide/reference/api/search/suggest/
# File lib/elasticsearch/api/actions/suggest.rb, line 29 def suggest(arguments={}) valid_params = [ :ignore_indices, :preference, :routing, :source ] method = HTTP_POST path = Utils.__pathify( Utils.__listify(arguments[:index]), '_suggest' ) params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
@deprecated Use the plural version, {#termvectors}
# File lib/elasticsearch/api/actions/termvectors.rb, line 92 def termvector(arguments={}) termvectors(arguments.merge :endpoint => '_termvector') end
Return information and statistics about terms in the fields of a particular document
@example Get statistics for an indexed document
client.indices.create index: 'my_index', body: { mappings: { my_type: { properties: { text: { type: 'string', term_vector: 'with_positions_offsets_payloads' } } } } } client.index index: 'my_index', type: 'my_type', id: '1', body: { text: 'Foo Bar Fox' } client.termvectors index: 'my_index', type: 'my_type', id: '1' # => { ..., "term_vectors" => { "text" => { "field_statistics" => { ... }, "terms" => { "bar" => ... } } }
@example Get statistics for an arbitrary document
client.termvector index: 'my_index', type: 'my_type', body: { doc: { text: 'Foo Bar Fox' } } # => { ..., "term_vectors" => { "text" => { "field_statistics" => { ... }, "terms" => { "bar" => ... } } }
@option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (Required) @option arguments [String] :id The document ID @option arguments [Hash] :body The request definition @option arguments [Boolean] :term_statistics Whether total term frequency and
document frequency should be returned
@option arguments [Boolean] :field_statistics Whether document count, sum of document frequencies
and sum of total term frequencies should be returned
@option arguments [List] :fields A comma-separated list of fields to return @option arguments [Boolean] :offsets Whether term offsets should be returned @option arguments [Boolean] :positions Whether term positions should be returned @option arguments [Boolean] :payloads Whether term payloads should be returned @option arguments [String] :preference Specify the node or shard the operation should be performed on
(default: random)
@option arguments [String] :realtime Specifies if requests are real-time as opposed to near-real-time
(default: true)
@option arguments [String] :routing Specific routing value @option arguments [String] :parent Parent ID of the documents
@see www.elasticsearch.org/guide/en/elasticsearch/reference/master/docs-termvectors.html
# File lib/elasticsearch/api/actions/termvectors.rb, line 60 def termvectors(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] valid_params = [ :term_statistics, :field_statistics, :fields, :offsets, :positions, :payloads, :preference, :realtime, :routing, :parent ] method = HTTP_GET endpoint = arguments.delete(:endpoint) || '_termvectors' path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), arguments[:id], endpoint params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] perform_request(method, path, params, body).body end
Update a document without sending the whole document in the request (“partial update”).
Send either a partial document (`doc` ) which will be deeply merged into an existing document, or a `script`, which will update the document content, in the `:body` argument.
The partial update operation allows you to limit the amount of data you send over the wire and reduces the chance of failed updates due to conflict.
Specify the `:version` and `:retry_on_conflict` arguments to balance convenience and consistency.
@example Update document title using partial `doc`-ument
client.update index: 'myindex', type: 'mytype', id: '1', body: { doc: { title: 'Updated' } }
@example Add a tag to document `tags` property using a `script`
client.update index: 'myindex', type: 'mytype', id: '1', body: { script: 'ctx._source.tags += tag', params: { tag: 'x' } }
@example Increment a document counter by 1 or initialize it, when the document does not exist
client.update index: 'myindex', type: 'mytype', id: '666', body: { script: 'ctx._source.counter += 1', upsert: { counter: 1 } }
@example Delete a document if it's tagged “to-delete”
client.update index: 'myindex', type: 'mytype', id: '1', body: { script: 'ctx._source.tags.contains(tag) ? ctx.op = "delete" : ctx.op = "none"', params: { tag: 'to-delete' } }
@option arguments [String] :id Document ID (Required) @option arguments [Number,List] :ignore The list of HTTP errors to ignore; only `404` supported at the moment @option arguments [String] :index The name of the index (Required) @option arguments [String] :type The type of the document (Required) @option arguments [Hash] :body The request definition using either `script` or partial `doc` (Required) @option arguments [String] :consistency Explicit write consistency setting for the operation
(options: one, quorum, all)
@option arguments [List] :fields A comma-separated list of fields to return in the response @option arguments [String] :lang The script language (default: mvel) @option arguments [String] :parent ID of the parent document @option arguments [String] :percolate Perform percolation during the operation;
use specific registered query name, attribute, or wildcard
@option arguments [Boolean] :refresh Refresh the index after performing the operation @option arguments [String] :replication Specific replication type (options: sync, async) @option arguments [Number] :retry_on_conflict Specify how many times should the operation be retried
when a conflict occurs (default: 0)
@option arguments [String] :routing Specific routing value @option arguments [String] :script The URL-encoded script definition (instead of using request body) @option arguments [Time] :timeout Explicit operation timeout @option arguments [Time] :timestamp Explicit timestamp for the document @option arguments [Duration] :ttl Expiration time for the document @option arguments [Number] :version Explicit version number for concurrency control @option arguments [Number] :version_type Explicit version number for concurrency control
@since 0.20
@see elasticsearch.org/guide/reference/api/update/
# File lib/elasticsearch/api/actions/update.rb, line 64 def update(arguments={}) raise ArgumentError, "Required argument 'index' missing" unless arguments[:index] raise ArgumentError, "Required argument 'type' missing" unless arguments[:type] raise ArgumentError, "Required argument 'id' missing" unless arguments[:id] valid_params = [ :consistency, :fields, :lang, :parent, :percolate, :refresh, :replication, :retry_on_conflict, :routing, :script, :timeout, :timestamp, :ttl, :version, :version_type ] method = HTTP_POST path = Utils.__pathify Utils.__escape(arguments[:index]), Utils.__escape(arguments[:type]), Utils.__escape(arguments[:id]), '_update' params = Utils.__validate_and_extract_params arguments, valid_params body = arguments[:body] params[:fields] = Utils.__listify(params[:fields]) if params[:fields] perform_request(method, path, params, body).body rescue Exception => e # NOTE: Use exception name, not full class in Elasticsearch::Client to allow client plugability if Array(arguments[:ignore]).include?(404) && e.class.to_s =~ /NotFound/; false else raise(e) end end