Class: Elastomer::Client
- Inherits:
-
Object
- Object
- Elastomer::Client
- Includes:
- Notifications
- Defined in:
- lib/elastomer/notifications.rb,
lib/elastomer/client.rb,
lib/elastomer/client/bulk.rb,
lib/elastomer/client/docs.rb,
lib/elastomer/client/index.rb,
lib/elastomer/client/nodes.rb,
lib/elastomer/client/errors.rb,
lib/elastomer/client/warmer.rb,
lib/elastomer/client/cluster.rb,
lib/elastomer/client/scroller.rb,
lib/elastomer/client/snapshot.rb,
lib/elastomer/client/template.rb,
lib/elastomer/client/percolator.rb,
lib/elastomer/client/repository.rb,
lib/elastomer/client/multi_search.rb,
lib/elastomer/client/delete_by_query.rb,
lib/elastomer/client/multi_percolate.rb
Overview
inject our instrument method into the Client class
Defined Under Namespace
Classes: Bulk, Cluster, DeleteByQuery, Docs, Error, Index, MultiPercolate, MultiSearch, Nodes, Percolator, Repository, Scroller, Snapshot, Template, Warmer
Constant Summary collapse
- TimeoutError =
Wrapper classes for specific Faraday errors.
Class.new Error
- ConnectionFailed =
Class.new Error
- ResourceNotFound =
Class.new Error
- ParsingError =
Class.new Error
- SSLError =
Class.new Error
- ServerError =
Class.new Error
- RequestError =
Class.new Error
- DEFAULT_OPTS =
{ :index => nil, :type => nil, :scroll => "5m", :size => 50, }.freeze
- OpaqueIdError =
Error raised when a conflict is detected between the UUID sent in the ‘X-Opaque-Id’ request header and the one received in the response header.
Class.new Client::Error
Constants included from Notifications
Instance Attribute Summary collapse
-
#host ⇒ Object
readonly
Returns the value of attribute host.
-
#open_timeout ⇒ Object
readonly
Returns the value of attribute open_timeout.
-
#port ⇒ Object
readonly
Returns the value of attribute port.
-
#read_timeout ⇒ Object
readonly
Returns the value of attribute read_timeout.
-
#url ⇒ Object
readonly
Returns the value of attribute url.
Instance Method Summary collapse
-
#assert_param_presence(param, name = "input value") ⇒ Object
Internal: Ensure that the parameter has a valid value.
-
#bulk(body = nil, params = nil) ⇒ Object
The ‘bulk` method can be used in two ways.
-
#bulk_stream_items(ops, params = {}) ⇒ Object
Stream bulk actions from an Enumerator and passes the response items to the given block.
-
#bulk_stream_responses(ops, params = {}) ⇒ Object
Stream bulk actions from an Enumerator.
-
#cluster ⇒ Object
Returns a Cluster instance.
-
#connection ⇒ Object
Internal: Provides access to the Faraday::Connection used by this client for all requests to the server.
-
#continue_scroll(scroll_id, scroll = "5m") ⇒ Object
Continue scrolling a query.
-
#delete(path, params = {}) ⇒ Object
Internal: Sends an HTTP DELETE request to the server.
-
#delete_by_query(query, params = {}) ⇒ Object
Delete documents from one or more indices and one or more types based on a query.
-
#docs(name = nil, type = nil) ⇒ Object
Provides access to document-level API commands.
-
#expand_path(path, params) ⇒ Object
Internal: Apply path expansions to the ‘path` and append query parameters to the `path`.
-
#extract_body(params) ⇒ Object
Internal: Extract the :body from the params Hash and convert it to a JSON String format.
-
#get(path, params = {}) ⇒ Object
Internal: Sends an HTTP GET request to the server.
-
#handle_errors(response) ⇒ Object
Internal: Inspect the Faraday::Response and raise an error if the status is in the 5XX range or if the response body contains an ‘error’ field.
-
#head(path, params = {}) ⇒ Object
Internal: Sends an HTTP HEAD request to the server.
-
#index(name = nil) ⇒ Object
Provides access to index-level API commands.
-
#info ⇒ Object
Returns the information Hash from the attached Elasticsearch instance.
-
#initialize(opts = {}) ⇒ Client
constructor
Create a new client that can be used to make HTTP requests to the Elasticsearch server.
-
#instrument(path, body, params) ⇒ Object
Internal: A noop method that simply yields to the block.
-
#is_ok?(item) ⇒ Boolean
Internal: Determine whether or not a response item has an HTTP status code in the range 200 to 299.
-
#multi_percolate(body = nil, params = nil) ⇒ Object
(also: #mpercolate)
Execute an array of percolate actions in bulk.
-
#multi_search(body = nil, params = nil) ⇒ Object
(also: #msearch)
Execute an array of searches in bulk.
-
#nodes(node_id = nil) ⇒ Object
Provides access to node-level API commands.
-
#ping ⇒ Object
(also: #available?)
Returns true if the server is available; returns false otherwise.
-
#post(path, params = {}) ⇒ Object
Internal: Sends an HTTP POST request to the server.
-
#put(path, params = {}) ⇒ Object
Internal: Sends an HTTP PUT request to the server.
-
#repository(name = nil) ⇒ Object
Returns a Repository instance.
-
#request(method, path, params) ⇒ Object
Internal: Sends an HTTP request to the server.
-
#scan(query, opts = {}) ⇒ Object
Create a new Scroller instance for scrolling all results from a ‘query` via “scan” semantics.
-
#scroll(query, opts = {}) ⇒ Object
Create a new Scroller instance for scrolling all results from a ‘query`.
-
#semantic_version ⇒ Object
Returns a Semantic::Version for the attached Elasticsearch instance.
-
#snapshot(repository = nil, name = nil) ⇒ Object
Provides access to snapshot API commands.
-
#start_scroll(opts = {}) ⇒ Object
Begin scrolling a query.
-
#template(name) ⇒ Object
Returns a Template instance.
-
#version ⇒ Object
Returns the version String of the attached Elasticsearch instance.
Constructor Details
#initialize(opts = {}) ⇒ Client
Create a new client that can be used to make HTTP requests to the Elasticsearch server.
opts - The options Hash
:host - the host as a String
:port - the port number of the server
:url - the URL as a String (overrides :host and :port)
:read_timeout - the timeout in seconds when reading from an HTTP connection
:open_timeout - the timeout in seconds when opening an HTTP connection
:adapter - the Faraday adapter to use (defaults to :excon)
:opaque_id - set to `true` to use the 'X-Opaque-Id' request header
24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/elastomer/client.rb', line 24 def initialize( opts = {} ) host = opts.fetch :host, "localhost" port = opts.fetch :port, 9200 @url = opts.fetch :url, "http://#{host}:#{port}" uri = Addressable::URI.parse @url @host = uri.host @port = uri.port @read_timeout = opts.fetch :read_timeout, 5 @open_timeout = opts.fetch :open_timeout, 2 @adapter = opts.fetch :adapter, Faraday.default_adapter @opaque_id = opts.fetch :opaque_id, false end |
Instance Attribute Details
#host ⇒ Object (readonly)
Returns the value of attribute host.
39 40 41 |
# File 'lib/elastomer/client.rb', line 39 def host @host end |
#open_timeout ⇒ Object (readonly)
Returns the value of attribute open_timeout.
40 41 42 |
# File 'lib/elastomer/client.rb', line 40 def open_timeout @open_timeout end |
#port ⇒ Object (readonly)
Returns the value of attribute port.
39 40 41 |
# File 'lib/elastomer/client.rb', line 39 def port @port end |
#read_timeout ⇒ Object (readonly)
Returns the value of attribute read_timeout.
40 41 42 |
# File 'lib/elastomer/client.rb', line 40 def read_timeout @read_timeout end |
#url ⇒ Object (readonly)
Returns the value of attribute url.
39 40 41 |
# File 'lib/elastomer/client.rb', line 39 def url @url end |
Instance Method Details
#assert_param_presence(param, name = "input value") ⇒ Object
Internal: Ensure that the parameter has a valid value. Strings, Symbols, Numerics, and Arrays of those things are valid. Things like ‘nil` and empty strings are right out. This method also performs a little formating on the parameter:
-
leading and trailing whitespace is removed
-
arrays are flattend
-
and then joined into a String
-
numerics are converted to their string equivalents
param - The param Object to validate name - Optional param name as a String (used in exception messages)
Returns the validated param as a String. Raises an ArgumentError if the param is not valid.
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/elastomer/client.rb', line 318 def assert_param_presence( param, name = "input value" ) case param when String, Symbol, Numeric param = param.to_s.strip raise ArgumentError, "#{name} cannot be blank: #{param.inspect}" if param =~ /\A\s*\z/ param when Array param.flatten.map { |item| assert_param_presence(item, name) }.join(",") when nil raise ArgumentError, "#{name} cannot be nil" else raise ArgumentError, "#{name} is invalid: #{param.inspect}" end end |
#bulk(body = nil, params = nil) ⇒ Object
The ‘bulk` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters. If given a block, the method will use a Bulk instance to assemble the operations called in the block into a bulk request and dispatch it at the end of the block.
See www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
body - Request body as a String (required if a block is not given) params - Optional request parameters as a Hash
:request_size - Optional maximum request size in bytes
:action_count - Optional maximum action size
block - Passed to a Bulk instance which assembles the operations
into one or more bulk requests.
Examples
bulk(request_body, :index => 'default-index')
bulk(:index => 'default-index') do |b|
b.index(document1)
b.index(document2, :_type => 'default-type')
b.delete(document3)
...
end
Returns the response body as a Hash
31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/elastomer/client/bulk.rb', line 31 def bulk( body = nil, params = nil ) if block_given? params, body = (body || {}), nil yield bulk_obj = Bulk.new(self, params) bulk_obj.call else raise "bulk request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_bulk", params.merge(:body => body, :action => "bulk") response.body end end |
#bulk_stream_items(ops, params = {}) ⇒ Object
Stream bulk actions from an Enumerator and passes the response items to the given block.
Examples
ops = [
[:index, document1, {:_type => "foo", :_id => 1}],
[:create, document2],
[:delete, {:_type => "bar", :_id => 42}]
]
bulk_stream_items(ops, :index => 'default-index') do |item|
puts item
end
# return value:
# {
# "took" => 256,
# "errors" => false,
# "success" => 3,
# "failure" => 0
# }
# sample response item:
# {
# "delete": {
# "_index": "foo",
# "_type": "bar",
# "_id": "42",
# "_version": 3,
# "status": 200,
# "found": true
# }
# }
Returns a Hash of stats about items from the responses.
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
# File 'lib/elastomer/client/bulk.rb', line 119 def bulk_stream_items(ops, params = {}) stats = { "took" => 0, "errors" => false, "success" => 0, "failure" => 0 } bulk_stream_responses(ops, params).each do |response| stats["took"] += response["took"] stats["errors"] |= response["errors"] response["items"].each do |item| if is_ok?(item) stats["success"] += 1 else stats["failure"] += 1 end yield item end end stats end |
#bulk_stream_responses(ops, params = {}) ⇒ Object
Stream bulk actions from an Enumerator.
Examples
ops = [
[:index, document1, {:_type => "foo", :_id => 1}],
[:create, document2],
[:delete, {:_type => "bar", :_id => 42}]
]
bulk_stream_responses(ops, :index => 'default-index').each do |response|
puts response
end
Returns an Enumerator of responses.
60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/elastomer/client/bulk.rb', line 60 def bulk_stream_responses(ops, params = {}) bulk_obj = Bulk.new(self, params) Enumerator.new do |yielder| ops.each do |action, *args| response = bulk_obj.send(action, *args) yielder.yield response unless response.nil? end response = bulk_obj.call yielder.yield response unless response.nil? end end |
#cluster ⇒ Object
Returns a Cluster instance.
5 6 7 |
# File 'lib/elastomer/client/cluster.rb', line 5 def cluster @cluster ||= Cluster.new self end |
#connection ⇒ Object
Internal: Provides access to the Faraday::Connection used by this client for all requests to the server.
Returns a Faraday::Connection
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/elastomer/client.rb', line 72 def connection @connection ||= Faraday.new(url) do |conn| conn.request :encode_json conn.response :parse_json conn.request :opaque_id if @opaque_id if @adapter.is_a?(Array) conn.adapter(*@adapter) else conn.adapter(@adapter) end conn.[:timeout] = read_timeout conn.[:open_timeout] = open_timeout end end |
#continue_scroll(scroll_id, scroll = "5m") ⇒ Object
Continue scrolling a query. See www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
scroll_id - The current scroll ID as a String scroll - The keep alive time of the scrolling request (5 minutes by default)
Examples
scroll_id = client.start_scroll('{"query":{"match_all":{}}}', :index => 'test', :search_type => 'scan')['_scroll_id']
h = client.continue_scroll scroll_id # scroll to get the next set of results
scroll_id = h['_scroll_id'] # and store the scroll_id to use later
h = client.continue_scroll scroll_id # scroll again to get the next set of results
scroll_id = h['_scroll_id'] # and store the scroll_id to use later
# repeat until the results are empty
Returns the response body as a Hash.
99 100 101 102 |
# File 'lib/elastomer/client/scroller.rb', line 99 def continue_scroll( scroll_id, scroll = "5m" ) response = get "/_search/scroll", :body => scroll_id, :scroll => scroll, :action => "search.scroll" response.body end |
#delete(path, params = {}) ⇒ Object
Internal: Sends an HTTP DELETE request to the server.
path - The path as a String params - Parameters Hash
Returns a Faraday::Response Raises an Elastomer::Client::Error on 4XX and 5XX responses
139 140 141 |
# File 'lib/elastomer/client.rb', line 139 def delete( path, params = {} ) request :delete, path, params end |
#delete_by_query(query, params = {}) ⇒ Object
Delete documents from one or more indices and one or more types based on a query.
The return value follows the format returned by the Elasticsearch Delete by Query plugin: github.com/elastic/elasticsearch/blob/master/docs/plugins/delete-by-query.asciidoc#response-body
Internally, this method uses a combination of scroll and bulk delete instead of the Delete by Query API, which was removed in Elasticsearch 2.0.
query - The query body as a Hash params - Parameters Hash
Examples
# request body query
delete_by_query({:query => {:match_all => {}}}, :type => 'tweet')
# same thing but using the URI request method
delete_by_query(nil, { :q => '*:*', :type => 'tweet' })
See www.elastic.co/guide/en/elasticsearch/plugins/current/delete-by-query-usage.html
Returns a Hash of statistics about the delete operations, for example:
{
"took" : 639,
"_indices" : {
"_all" : {
"found" : 5901,
"deleted" : 5901,
"missing" : 0,
"failed" : 0
},
"twitter" : {
"found" : 5901,
"deleted" : 5901,
"missing" : 0,
"failed" : 0
}
},
"failures" : [ ]
}
47 48 49 |
# File 'lib/elastomer/client/delete_by_query.rb', line 47 def delete_by_query(query, params = {}) DeleteByQuery.new(self, query, params).execute end |
#docs(name = nil, type = nil) ⇒ Object
Provides access to document-level API commands. Indexing documents and searching documents are both handled by this module.
name - The name of the index as a String (optional) type - The document type as a String (optional)
See www.elastic.co/guide/en/elasticsearch/reference/current/docs.html
Returns a Docs instance.
14 15 16 |
# File 'lib/elastomer/client/docs.rb', line 14 def docs( name = nil, type = nil ) Docs.new self, name, type end |
#expand_path(path, params) ⇒ Object
Internal: Apply path expansions to the ‘path` and append query parameters to the `path`. We are using an Addressable::Template to replace ’expansion‘ fields found in the path with the values extracted from the `params` Hash. Any remaining elements in the `params` hash are treated as query parameters and appended to the end of the path.
path - The path as a String params - Parameters Hash
Examples
expand_path('/foo{/bar}', {:bar => 'hello', :q => 'what', :p => 2})
#=> '/foo/hello?q=what&p=2'
expand_path('/foo{/bar}{/baz}', {:baz => 'no bar'}
#=> '/foo/no%20bar'
Returns an Addressable::Uri
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
# File 'lib/elastomer/client.rb', line 251 def ( path, params ) template = Addressable::Template.new path expansions = {} query_values = params.dup query_values.delete :action query_values.delete :context template.keys.map(&:to_sym).each do |key| value = query_values.delete key value = assert_param_presence(value, key) unless path =~ /{\/#{key}}/ && value.nil? expansions[key] = value end uri = template.(expansions) uri.query_values = query_values unless query_values.empty? uri.to_s end |
#extract_body(params) ⇒ Object
Internal: Extract the :body from the params Hash and convert it to a JSON String format. If the params Hash does not contain a :body then no action is taken and ‘nil` is returned.
If a :body is present and is a String then it is assumed to a JSON String and returned “as is”.
If a :body is present and is an Array then we join the values together with newlines and append a trailing newline. This is a special case for dealing with ES ‘bulk` imports and `multi_search` methods.
Otherwise we convert the :body to a JSON string and return.
params - Parameters Hash
Returns the request body as a String or ‘nil` if no :body is present
218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/elastomer/client.rb', line 218 def extract_body( params ) body = params.delete :body return if body.nil? case body when String body when Array body << nil unless body.last.nil? body.join "\n" else MultiJson.dump body end end |
#get(path, params = {}) ⇒ Object
Internal: Sends an HTTP GET request to the server.
path - The path as a String params - Parameters Hash
Returns a Faraday::Response Raises an Elastomer::Client::Error on 4XX and 5XX responses
106 107 108 |
# File 'lib/elastomer/client.rb', line 106 def get( path, params = {} ) request :get, path, params end |
#handle_errors(response) ⇒ Object
Internal: Inspect the Faraday::Response and raise an error if the status is in the 5XX range or if the response body contains an ‘error’ field. In the latter case, the value of the ‘error’ field becomes our exception message. In the absence of an ‘error’ field the response body is used as the exception message.
The raised exception will contain the response object.
response - The Faraday::Response object.
Returns the response. Raises an Elastomer::Client::Error on 500 responses or responses containing and ‘error’ field.
296 297 298 299 300 301 |
# File 'lib/elastomer/client.rb', line 296 def handle_errors( response ) raise ServerError, response if response.status >= 500 raise RequestError, response if response.body.is_a?(Hash) && response.body["error"] response end |
#head(path, params = {}) ⇒ Object
Internal: Sends an HTTP HEAD request to the server.
path - The path as a String params - Parameters Hash
Returns a Faraday::Response
95 96 97 |
# File 'lib/elastomer/client.rb', line 95 def head( path, params = {} ) request :head, path, params end |
#index(name = nil) ⇒ Object
Provides access to index-level API commands. An index name is required for these API calls. If you want to operate on all indices - flushing all indices, for example - then you will need to use the “_all” index name.
You can override the index name for one-off calls by passing in the desired index name via the ‘:index` option.
name - The name of the index as a String or an Array of names
Returns an Index instance.
14 15 16 |
# File 'lib/elastomer/client/index.rb', line 14 def index( name = nil ) Index.new self, name end |
#info ⇒ Object
Returns the information Hash from the attached Elasticsearch instance.
63 64 65 66 |
# File 'lib/elastomer/client.rb', line 63 def info response = get "/", :action => "cluster.info" response.body end |
#instrument(path, body, params) ⇒ Object
Internal: A noop method that simply yields to the block. This method will be replaced when the ‘elastomer/notifications’ module is included.
path - The full request path as a String body - The request body as a String or ‘nil` params - The request params Hash block - The block that will be instrumented
Returns the response from the block
279 280 281 |
# File 'lib/elastomer/client.rb', line 279 def instrument( path, body, params ) yield end |
#is_ok?(item) ⇒ Boolean
Internal: Determine whether or not a response item has an HTTP status code in the range 200 to 299.
item - The bulk response item
Returns a boolean
80 81 82 |
# File 'lib/elastomer/client/bulk.rb', line 80 def is_ok?(item) item.values.first["status"].between?(200, 299) end |
#multi_percolate(body = nil, params = nil) ⇒ Object Also known as: mpercolate
Execute an array of percolate actions in bulk. Results are returned in an array in the order the actions were sent.
The ‘multi_percolate` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters.
See www.elastic.co/guide/en/elasticsearch/reference/current/search-percolate.html#_multi_percolate_api
body - Request body as a String (required if a block is not given) params - Optional request parameters as a Hash block - Passed to a MultiPercolate instance which assembles the
percolate actions into a single request.
Examples
# index and type in request body
multi_percolate(request_body)
# index in URI
multi_percolate(request_body, :index => 'default-index')
# block form
multi_percolate(:index => 'default-index') do |m|
m.percolate({ :author => "pea53" }, { :type => 'default-type' })
m.count({ :author => "pea53" }, { :type => 'type2' })
...
end
Returns the response body as a Hash
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/elastomer/client/multi_percolate.rb', line 34 def multi_percolate(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield mpercolate_obj = MultiPercolate.new(self, params) mpercolate_obj.call else raise "multi_percolate request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_mpercolate", params.merge(:body => body) response.body end end |
#multi_search(body = nil, params = nil) ⇒ Object Also known as: msearch
Execute an array of searches in bulk. Results are returned in an array in the order the queries were sent.
The ‘multi_search` method can be used in two ways. Without a block the method will perform an API call, and it requires a bulk request body and optional request parameters.
See www.elastic.co/guide/en/elasticsearch/reference/current/search-multi-search.html
body - Request body as a String (required if a block is not given) params - Optional request parameters as a Hash block - Passed to a MultiSearch instance which assembles the searches
into a single request.
Examples
# index and type in request body
multi_search(request_body)
# index in URI
multi_search(request_body, :index => 'default-index')
# block form
multi_search(:index => 'default-index') do |m|
m.search({:query => {:match_all => {}}, :search_type => :count)
m.search({:query => {:field => {"foo" => "bar"}}}, :type => 'default-type')
...
end
Returns the response body as a Hash
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/elastomer/client/multi_search.rb', line 34 def multi_search(body = nil, params = nil) if block_given? params, body = (body || {}), nil yield msearch_obj = MultiSearch.new(self, params) msearch_obj.call else raise "multi_search request body cannot be nil" if body.nil? params ||= {} response = self.post "{/index}{/type}/_msearch", params.merge(:body => body) response.body end end |
#nodes(node_id = nil) ⇒ Object
Provides access to node-level API commands. The default node is set to nil which target all nodes. You can pass in “_all” (to get the same effect) or “_local” to target only the current node the client is connected to. And you can specify an individual node or multiple nodes.
node_id - The node ID as a String or an Array of node IDs
Returns a Nodes instance.
13 14 15 |
# File 'lib/elastomer/client/nodes.rb', line 13 def nodes( node_id = nil ) Nodes.new self, node_id end |
#ping ⇒ Object Also known as: available?
Returns true if the server is available; returns false otherwise.
43 44 45 46 47 48 |
# File 'lib/elastomer/client.rb', line 43 def ping response = head "/", :action => "cluster.ping" response.success? rescue StandardError false end |
#post(path, params = {}) ⇒ Object
Internal: Sends an HTTP POST request to the server.
path - The path as a String params - Parameters Hash
Returns a Faraday::Response Raises an Elastomer::Client::Error on 4XX and 5XX responses
128 129 130 |
# File 'lib/elastomer/client.rb', line 128 def post( path, params = {} ) request :post, path, params end |
#put(path, params = {}) ⇒ Object
Internal: Sends an HTTP PUT request to the server.
path - The path as a String params - Parameters Hash
Returns a Faraday::Response Raises an Elastomer::Client::Error on 4XX and 5XX responses
117 118 119 |
# File 'lib/elastomer/client.rb', line 117 def put( path, params = {} ) request :put, path, params end |
#repository(name = nil) ⇒ Object
Returns a Repository instance.
5 6 7 |
# File 'lib/elastomer/client/repository.rb', line 5 def repository(name = nil) Repository.new(self, name) end |
#request(method, path, params) ⇒ Object
Internal: Sends an HTTP request to the server. If the ‘params` Hash contains a :body key, it will be deleted from the Hash and the value will be used as the body of the request.
method - The HTTP method to send [:head, :get, :put, :post, :delete] path - The path as a String params - Parameters Hash
:body - Will be used as the request body
:read_timeout - Optional read timeout (in seconds) for the request
Returns a Faraday::Response Raises an Elastomer::Client::Error on 4XX and 5XX responses rubocop:disable Metrics/MethodLength
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/elastomer/client.rb', line 156 def request( method, path, params ) read_timeout = params.delete :read_timeout body = extract_body params path = path, params instrument(path, body, params) do begin response = case method when :head connection.head(path) { |req| req.[:timeout] = read_timeout if read_timeout } when :get connection.get(path) { |req| req.body = body if body req.[:timeout] = read_timeout if read_timeout } when :put connection.put(path, body) { |req| req.[:timeout] = read_timeout if read_timeout } when :post connection.post(path, body) { |req| req.[:timeout] = read_timeout if read_timeout } when :delete connection.delete(path) { |req| req.body = body if body req.[:timeout] = read_timeout if read_timeout } else raise ArgumentError, "unknown HTTP request method: #{method.inspect}" end handle_errors response # wrap Faraday errors with appropriate Elastomer::Client error classes rescue Faraday::Error::ClientError => boom error_name = boom.class.name.split("::").last error_class = Elastomer::Client.const_get(error_name) rescue Elastomer::Client::Error raise error_class.new(boom, method.upcase, path) end end end |
#scan(query, opts = {}) ⇒ Object
Create a new Scroller instance for scrolling all results from a ‘query` via “scan” semantics.
query - The query to scan as a Hash or a JSON encoded String opts - Options Hash
:index - the name of the index to search
:type - the document type to search
:scroll - the keep alive time of the scrolling request (5 minutes by default)
:size - the number of documents per shard to fetch per scroll
Examples
scan = client.scan('{"query":{"match_all":{}}}', :index => 'test')
scan.each_document do |document|
document['_id']
document['_source']
end
Returns a new Scroller instance
45 46 47 48 |
# File 'lib/elastomer/client/scroller.rb', line 45 def scan( query, opts = {} ) opts = opts.merge(:search_type => "scan") Scroller.new(self, query, opts) end |
#scroll(query, opts = {}) ⇒ Object
Create a new Scroller instance for scrolling all results from a ‘query`.
query - The query to scroll as a Hash or a JSON encoded String opts - Options Hash
:index - the name of the index to search
:type - the document type to search
:scroll - the keep alive time of the scrolling request (5 minutes by default)
:size - the number of documents per shard to fetch per scroll
Examples
scroll = client.scroll('{"query":{"match_all":{}}}', :index => 'test')
scroll.each_document do |document|
document['_id']
document['_source']
end
Returns a new Scroller instance
22 23 24 |
# File 'lib/elastomer/client/scroller.rb', line 22 def scroll( query, opts = {} ) Scroller.new(self, query, opts) end |
#semantic_version ⇒ Object
Returns a Semantic::Version for the attached Elasticsearch instance. See rubygems.org/gems/semantic
58 59 60 |
# File 'lib/elastomer/client.rb', line 58 def semantic_version Semantic::Version.new(version) end |
#snapshot(repository = nil, name = nil) ⇒ Object
Provides access to snapshot API commands.
repository - The name of the repository as a String name - The name of the snapshot as a String
Returns a Snapshot instance.
10 11 12 |
# File 'lib/elastomer/client/snapshot.rb', line 10 def snapshot(repository = nil, name = nil) Snapshot.new self, repository, name end |
#start_scroll(opts = {}) ⇒ Object
Begin scrolling a query. See www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
opts - Options Hash
:query - the query to scroll as a Hash or JSON encoded String
:index - the name of the index to search
:type - the document type to search
:scroll - the keep alive time of the scrolling request (5 minutes by default)
:size - the number of documents per shard to fetch per scroll
:search_type - set to 'scan' for scan semantics
Examples
h = client.start_scroll('{"query":{"match_all":{}},"sort":{"created":"desc"}}', :index => 'test')
scroll_id = h['_scroll_id']
h['hits']['hits'].each { |doc| ... }
h = client.continue_scroll(scroll_id)
scroll_id = h['_scroll_id']
h['hits']['hits'].each { |doc| ... }
# repeat until there are no more hits
Returns the response body as a Hash.
74 75 76 77 78 |
# File 'lib/elastomer/client/scroller.rb', line 74 def start_scroll( opts = {} ) opts = opts.merge :action => "search.start_scroll" response = get "{/index}{/type}/_search", opts response.body end |
#template(name) ⇒ Object
Returns a Template instance.
6 7 8 |
# File 'lib/elastomer/client/template.rb', line 6 def template( name ) Template.new self, name end |
#version ⇒ Object
Returns the version String of the attached Elasticsearch instance.
52 53 54 |
# File 'lib/elastomer/client.rb', line 52 def version @version ||= info["version"]["number"] end |