【问题标题】:Thinking Sphinx: Multiple indices for single model?Thinking Sphinx:单个模型的多个索引?
【发布时间】:2012-01-05 20:28:23
【问题描述】:

我正在使用 Thinking Sphinx 以两种不同的模式进行搜索:

  1. 在单个模型上进行完整搜索以实现正常搜索功能
  2. 全面搜索所有型号的自动完成下拉功能

为了这个问题,假设我有一个 Person 和一个 Country 模型。

在执行常规搜索时,我想获取所有国家名称与搜索字符串匹配的人。为此,我在 Person 索引中添加了国家名称的索引。到目前为止一切顺利。

在搜索以填充我的自动完成下拉列表时,我想显示与我的搜索字符串匹配的所有国家和所有人。这里问题出现了。在进行应用程序范围的搜索时,我现在得到:

  1. 名称与我的搜索字符串匹配的所有国家/地区
  2. 姓名与我的搜索字符串匹配的所有医生,不幸的是...
  3. 属于与搜索字符串匹配的国家/地区的所有医生。

最后一部分为用户提供了一些真正令人困惑的自动完成结果。有没有什么简单的方法可以通过使用内置功能来避免这种情况,例如在 Person 模型上有两个索引,然后为每种搜索选择使用哪个索引?

【问题讨论】:

    标签: search thinking-sphinx


    【解决方案1】:

    我认为你的模型如下所示:

    class Person < ActiveRecord::Base
      belongs_to :country
      define_index
        indexes :name
        indexes country(:name), :as => country_name
      end
    end
    
    class Country < ActiveRecord::Base
      has_many :people # has_many :persons # depending on your singular/plural case
      define_index
        indexes :name
      end
    end
    

    所以,你可以通过执行查询得到没有3(第三个条件)的结果:

    ThinkingSphinx.search :conditions => {:name => params[:q]}, :classes => [Person, Country]
    

    但是,如果您想在模型上创建多个索引,可以像下面的示例一样完成:

    class Person < ActiveRecord::Base
      belongs_to :country
      define_index :my_first_in do
        indexes :name
        indexes country(:name)
      end
      define_index :my_second_in do
        indexes :name
      end
    end
    

    【讨论】:

    • 仅适用于遇到此问题但不确定的任何人 - 此 define_index 语法适用于 v3 之前的 Thinking Sphinx 版本。
    【解决方案2】:

    上述答案的sphinx v3语法:

    ThinkingSphinx::Index.define :country, name: "my_first_in", with: :active_record
      indexes name
    end
    

    【讨论】:

    • 能否指定新版Sphinx的版本号?
    • 这是 v3 以后的语法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多