太阳黑子搜索订购

时间:2012-01-30 21:38:34

标签: ruby-on-rails ruby ruby-on-rails-3 solr sunspot

我正在使用太阳黑子(https://github.com/sunspot/sunspot)和Rails。

这是我的模特:

class Item < ActiveRecord::Base
  searchable do
    boolean :red
    boolean :blue
    boolean :green
    ...
  end
end

考虑以下搜索:

Item.search
  any_of do
    with :red, true
    with :blue, true
    with :green, true
  end
end

如何订购这样的结果:包含所有颜色的项目,后跟包含2种颜色的项目,后跟包含1种颜色的项目?

注意:这只是一个示例搜索。答案应该考虑颜色的所有可能的搜索组合。

更新1

按颜色数排序不起作用。例如,假设您有以下项目:

  1. 绿/蓝
  2. 绿色/红色/黑色
  3. 如果搜索绿色和蓝色,则第2项将在第1项之前。

2 个答案:

答案 0 :(得分:0)

丑陋,但可能会做到这一点:

class Item < ActiveRecord::Base
  searchable do
    boolean :red
    boolean :blue
    boolean :green
    integer :number_of_colors, :stored => true
  end

  def number_of_colors
    # implementation may vary
    count=0
    self.attributes.each do |k,v|
      if %w(red blue green).include?(k.to_s) && v?
        count += 1
      end
    end
    count
  end
end

然后,重新编制索引后:

Item.search
  any_of do
    with :red, true
    with :blue, true
    with :green, true
    order_by :number_of_colors, :desc
  end
end

希望这有帮助。

答案 1 :(得分:0)

哦!我不认为那里有其他颜色...感谢更新。在这种情况下,另一个选项是在可搜索块中的一个text字段中折叠所有对象的颜色代码(名称),然后使用所有需要在该字段上运行全文搜索颜色作为关键字。获得更多匹配的对象将获得最高的相关性分数,并将首先返回。类似的东西:

class Item < ActiveRecord::Base
  searchable do
    text :color_codes, :stored => true
  end

  # will return "green blue " for item1 above
  # will return "green red black " for item2 above
  def color_codes
    # implementation may vary
    colors=""
    self.attributes.each do |k,v|
      if %w(red blue green black ...).include?(k.to_s) && v?
        colors += "#{k} "
      end
    end
    colors
  end
end

然后,您的搜索例程如下:

q = "green blue"
Item.search do
  keywords q do
    fields :color_codes
  end
end

上面的第1项在“绿色蓝色”上搜索时会得到完全匹配,并且会先出现。