class Indexers::Indexer

Attributes

name[R]
options[R]

Public Class Methods

new(name, options) click to toggle source
# File lib/indexers/indexer.rb, line 6
def initialize(name, options)
  @name = name
  @options = options
end

Public Instance Methods

<=>(other) click to toggle source
# File lib/indexers/indexer.rb, line 23
def <=>(other)
  if has_parent? && other.has_parent?
    0
  elsif other.has_parent?
    1
  else
    -1
  end
end
any?(*args) click to toggle source
# File lib/indexers/indexer.rb, line 33
def any?(*args)
  search(*args).count > 0
end
build() click to toggle source
# File lib/indexers/indexer.rb, line 94
def build
  client.indices.put_mapping(
    index: namespace,
    type: name,
    body: mappings
  )
  model.find_in_batches do |records|
    client.bulk(
      index: namespace,
      type: name,
      body: records.map do |record|
        { index: with_parent(record, _id: record.id, data: serialize(record)) }
      end
    )
  end
end
exists?(record) click to toggle source
# File lib/indexers/indexer.rb, line 49
def exists?(record)
  client.exists?(
    with_parent(
      record,
      index: namespace,
      type: name,
      id: record.id
    )
  )
end
has_parent?() click to toggle source
# File lib/indexers/indexer.rb, line 19
def has_parent?
  mappings.has_key? :_parent
end
index(record) click to toggle source
# File lib/indexers/indexer.rb, line 60
def index(record)
  client.create(
    with_parent(
      record,
      index: namespace,
      type: name,
      id: record.id,
      body: serialize(record)
    )
  )
end
mappings() click to toggle source
# File lib/indexers/indexer.rb, line 15
def mappings
  @mappings ||= Dsl::Mappings.new(&options[:mappings]).to_h
end
model() click to toggle source
# File lib/indexers/indexer.rb, line 11
def model
  options.fetch(:class_name, name.to_s.classify).constantize
end
none?(*args) click to toggle source
# File lib/indexers/indexer.rb, line 37
def none?(*args)
  !any?(*args)
end
reindex(record) click to toggle source
# File lib/indexers/indexer.rb, line 72
def reindex(record)
  client.bulk(
    index: namespace,
    type: name,
    body: [
      { delete: with_parent(record, _id: record.id) },
      { index: with_parent(record, _id: record.id, data: serialize(record)) }
    ]
  )
end
unindex(record) click to toggle source
# File lib/indexers/indexer.rb, line 83
def unindex(record)
  client.delete(
    with_parent(
      record,
      index: namespace,
      type: name,
      id: record.id
    )
  )
end

Private Instance Methods

serialize(record) click to toggle source
# File lib/indexers/indexer.rb, line 127
def serialize(record)
  Dsl::Serialization.new(self, record, &options[:serialize]).to_h
end
with_parent(record, hash) click to toggle source
# File lib/indexers/indexer.rb, line 119
def with_parent(record, hash)
  if has_parent?
    hash.merge parent: record.send("#{mappings[:_parent][:type]}_id")
  else
    hash
  end
end