Skip to content

Instantly share code, notes, and snippets.

@pat
Created January 21, 2015 08:43
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 pat/971307984434f564bb50 to your computer and use it in GitHub Desktop.
Save pat/971307984434f564bb50 to your computer and use it in GitHub Desktop.
Mixing Apartment with Thinking Sphinx
# app/lib/index_set.rb
class IndexSet < ThinkingSphinx::IndexSet
private
def indices
# respect index names if they're provided
return super if index_names.any?
# filter indices by current tenant.
suffix = "#{Apartment::Tenant.current_tenant}_core"
super.select { |index| index.name[/_#{suffix}$/] }
end
end
# config/initializers/thinking_sphinx.rb
ThinkingSphinx::Configuration.instance.index_set_class = IndexSet
# app/indices/user_index.rb
current_tenant = Apartment::Tenant.current_tenant
# Each Enterprise instance is tied to a tenant in this example.
Enterprise.find_each do |enterprise|
# Switch to the appropriate Apartment tenant.
Apartment::Tenant.switch enterprise.slug
# Sphinx indices can't have hyphens in their name.
ThinkingSphinx::Index.define(
:user, name: "user_#{enterprise.slug.gsub('-', '_')}",
offset_as: "user_#{enterprise.slug.gsub('-', '_')}".to_sym,
with: :real_time
) do
indexes name
# For real-time indices, let's make sure we're using the appropriate tenant.
scope { Apartment::Tenant.switch enterprise.slug; User }
end
end if Enterprise.table_exists?
# Switching back to the original tenant - this is useful in the development
# environment, as indices (and thus, this file) can be reloaded, and we don't
# want to always leave our app on our last tenant.
Apartment::Tenant.switch current_tenant
@klippx
Copy link

klippx commented Feb 12, 2015

Can't wait to try this and see if I can get rid of my VIEW hack. It looks very promising.

In the mean time, I have a question. If I have a model called Item, which is indexed by ItemIndex, I would get two files on disk: item_core & item_delta.

Now suppose that I am using Apartment and I have 2 tenants called "greg" and "elise"....
Would I then get FOUR files on disk?

  • greg_item_core & greg_item_delta
  • elise_item_core & elise_item_delta

Or would I (pray) get only 2 files no matter how many tenants there are:

  • still simply item_core & item_delta

Can you explain how this will work with respect to how sphinx config will look, and what the physical files on disk will look like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment