思考Sphinx并搜索多个模型

我正在寻找一种方法来对多个模型进行搜索(参见这篇文章 ),并得到了几个答案,说思维狮身人面像将是一个很好的匹配这种事情。

事实上,它看起来很甜美,似乎应用程序范围的搜索function( ThinkingSphinx.search )接近我想要的。 但文档声明这将返回各种模型对象,具体取决于找到匹配的位置。

我的模特有点像这样:

  • 雇员
  • 公司

员工只通过公司与县相关联,公司又与市政府相关联,而市政府又与实际的县相关联。

现在作为搜索的结果,我真的只想要Employee对象。 例如,搜索字符串“joe tulsa”应返回所有Employees,其中两个单词都可以在命名模型中的某处找到。 我会得到一些误报,但至少我应该让塔尔萨县的每个员工都叫“乔”。

这是可以通过Thinking Sphinx的内置function实现的吗?

我认为在这种情况下你应该做的是定义你的Employee模型的关联(你可能已经有),例如:

 class Employee < ActiveRecord::Base ... belongs_to :company has_one :municipality, :through => :company has_one :county, :through => :company ... end class Company < ActiveRecord::Base ... belongs_to :municipality has_many :employees has_one :county, :through => :municipality ... end class Municipality < ActiveRecord::Base ... belongs_to :county has_many :companies ... end class County < ActiveRecord::Base ... has_many :municipalities ... end 

编辑:我测试了多级has_one关系,它不能像那样工作。 对这4层进行建模而不进行非规范化似乎相当复杂。 如果我拿出一些东西,我会更新。 在任何情况下,如果您进行非规范化(即向所有模型添加冗余外部ID到您的employees表),则关联很简单,并且您会大量增加索引生成时间。 同时,它可能涉及更多工作以确保一致性。

设置关联后,您可以在Employee模型中定义Sphinx索引,如下所示:

 define_index do indexes :name, :sortable => :true indexes company(:name), :as => :company indexes municipality(:name), :as => :municipality indexes county(:name), :as => :county ... end 

这样,关联中的列也会被编入索引,并且Sphinx会在构建索引时自动将所有这些表连接在一起。