【问题标题】:Sunspot search ordering太阳黑子搜索排序
【发布时间】:2012-01-30 21:38:33
【问题描述】:

我在 Rails 中使用 Sunspot (https://github.com/sunspot/sunspot)。

这是我的模型:

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 项之前。

【问题讨论】:

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


    【解决方案1】:

    丑陋,但可能会成功:

    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
    

    希望这会有所帮助。

    【讨论】:

    • 好主意,但我认为它行不通。请参阅上面的更新。
    【解决方案2】:

    哦!我不认为还有其他颜色在起作用...感谢您的更新。在这种情况下,另一种选择是在可搜索块中的一个 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
    

    上面的item1在“green blue”搜索时会得到完全匹配,并且会首先出现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 2014-03-29
      • 1970-01-01
      • 2014-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多