Last active
August 29, 2015 14:11
-
-
Save mjquinlan2000/23549723d5a8ea74e636 to your computer and use it in GitHub Desktop.
Chewy/Rails: Unique index per ActiveRecord object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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