2012-01-30 66 views
0

我使用的是太阳黑子(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. 绿/红/黑

如果您搜索绿色和蓝色,第2项会项目之前1.

回答

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 

希望这有助于。

+0

好主意,但我不认为它会工作。看到我上面的更新。 – Austin 2012-01-31 00:50:19

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的“绿蓝”搜索时上面会得到精确匹配,并会拿出第一。