Skip to content

Instantly share code, notes, and snippets.

@mjquinlan2000
Last active August 29, 2015 14:11
Show Gist options
  • Save mjquinlan2000/23549723d5a8ea74e636 to your computer and use it in GitHub Desktop.
Save mjquinlan2000/23549723d5a8ea74e636 to your computer and use it in GitHub Desktop.
Chewy/Rails: Unique index per ActiveRecord object
namespace :elasticsearch do
task import: :environment do
Organization.all.each do |organization|
organization.index.types.each do |type|
model = type.adapter.name.constantize
data = model.all_data_for organization
type.import data
end
end
end
end
class Organization < ActiveRecord::Base
def chewy_index
# Get the index by an organization's unique identifier
OrganizationIndexes.find_by_id self.unique_identifer
end
end
module OrganizationIndexes
@indexes = {}
def self.find_by_id(id)
@indexes[id] ||= define_index(id)
end
private
def self.define_index(id)
Class.new(Chewy::Index) do
# Unique index name here
index_name id
# Define your models here
define_type Foo do
field :some, :fields, :here
end
define_type Bar do
field :more, :fields, :there
end
end
end
end
class SearchController < ApplicationController
def search
# Search your organization index like this
@result = current_user.organization.chewy_index.query params[:q]
render @result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment