Skip to content

Instantly share code, notes, and snippets.

@alfius
Created September 22, 2016 21:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alfius/45c04600cc65a4c47619488744b696b6 to your computer and use it in GitHub Desktop.
Save alfius/45c04600cc65a4c47619488744b696b6 to your computer and use it in GitHub Desktop.
A simplified version of our Elasticsearch query library at Wootric, including a few examples
require 'rest-client'
require 'json'
class Elasticsearch
class << self
attr_accessor :url
def configured?
url.present?
end
def create_index(name, options = {})
response = RestClient.put "#{url}/#{name}", options.to_json
fail if JSON.parse(response.body)['acknowledged'] != true
end
def delete_index(name)
response = RestClient.delete "#{url}/#{name}"
fail if JSON.parse(response.body)['acknowledged'] != true
end
def index_exists?(name)
RestClient.head "#{url}/#{name}"
return true
rescue RestClient::ResourceNotFound
return false
end
def index_document(index_name:, type:, document:, options: {})
response = RestClient::Request.execute(
method: 'PUT',
url: "#{url}/#{index_name}/#{type}/#{document[:id]}",
headers: { params: options },
payload: document.to_json
)
fail unless JSON.parse(response.body)['_shards']['successful'] >= 1
end
def delete_document(index_name:, type:, id:, options: {})
response = RestClient::Request.execute(
method: 'DELETE',
url: "#{url}/#{index_name}/#{type}/#{id}",
headers: { params: options }
)
fail unless JSON.parse(response.body)['_shards']['successful'] >= 1
end
def search(index_name:, type: nil, query:, options: {})
payload = { query: query }.merge(options).to_json
Rails.logger.debug "Elasticsearch query: #{payload}"
response = RestClient::Request.execute(
method: 'GET',
url: "#{url}/#{index_name}/#{type ? type + '/' : ''}_search",
payload: payload
)
JSON.parse(response.body)
end
end
end
require 'elasticsearch'
Elasticsearch.url = 'http://localhost:9200'
# index a document:
Elasticsearch.index_document(
type: 'responses',
document: { id: 1, score: 10, text: '<3' }.to_json
)
# find documents:
ids = Elasticsearch.search(
type: 'responses',
query: { match: { score: 10 } },
)['hits']['hits'].map { |r| r['_id'].to_i }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment