class DCA::ElasticSearchStorage

Attributes

type[R]

Public Class Methods

establish_connection(config) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 11
def self.establish_connection(config)
  RestClient.get("http://#{config[:host]}:#{config[:port]}")
  Tire.configure { url "http://#{config[:host]}:#{config[:port]}" }
end
new(connection, context, options = {}) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 5
def initialize(connection, context, options = {})
  @connection = connection
  @index = options[:index] || DCA.project_name.underscore
  @type = options[:type] || get_alias(context)
end

Public Instance Methods

context(object) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 69
def context object
  result = self.clone
  result.instance_variable_set :@type, get_alias(object)
  result
end
create(item) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 36
def create(item)
  item.updated_at = item.created_at = Time.now.utc
  data = hash_from item

  result = Tire.index(@index).store data
  Tire.index(@index).refresh

  item.id = result['_id']
end
find(position) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 26
def find position
  return nil if position.base_id.nil?
  query = Tire.search(@index, type: type) { query { term :base_id, position.base_id } }
  query.results.first
end
index(&block) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 63
def index(&block)
  Tire.index @index do
    instance_eval(&block) if block_given?
  end
end
refresh(item, state) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 32
def refresh(item, state)
  send state, item
end
remove(item) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 54
def remove(item)
  data = hash_from item

  Tire.index(@index) do
    remove data
    refresh
  end
end
state(position) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 16
def state position
  item = find position
  return :create if item.nil?

  position.id = item[:id]
  return :unmodified if item[:checksum] == position.checksum

  :update
end
update(item) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 46
def update(item)
  data = hash_from item
  Tire.index(@index) do
    store data
    refresh
  end
end

Private Instance Methods

get_alias(object) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 85
def get_alias object
  object.respond_to?(:alias) ? object.alias : object.to_s.demodulize.downcase.pluralize
end
hash_from(item) click to toggle source
# File lib/dca/storage/elasticsearch_storage.rb, line 77
def hash_from(item)
  data = item.to_hash
  data[:_id] = data[:id] if data[:id]
  data.delete(:id)
  data[:type] = type
  data
end