【问题标题】:Conditional order_by depending on data in Sunspot条件 order_by 取决于 Sunspot 中的数据
【发布时间】:2013-03-25 14:38:18
【问题描述】:

我想知道是否有一种方法可以使用某种if/then 语义进行排序。

我试图解决的基本要求是:

  • 我的记录有一个contact_again_time时间属性,可以是nil
  • 列表的排序方式应使所有具有contact_again_time 的记录首先按contact_again_time 降序排列。
  • contact_again_time 为 nil 的其余部分应按 created_at 升序排序。

因此,我可以通过让我的searchable 看起来像这样将订单字段具体化到索引中来解决这个问题:

integer :sort_key do                                                                                                                                             
  contact_again_time.nil? ? (created_at.to_i * -1) : contact_again_time.to_i                                                                                     
end

然后做一个order_by(:sort_key, :desc) 得到我想要的。 但是通过这种方式,我将部分排序逻辑放在了我的模型中,更重要的是放在了 Lucene 索引中。

我宁愿避免的事情,因为它感觉很不对。

【问题讨论】:

    标签: ruby-on-rails solr sunspot


    【解决方案1】:

    在 Solr 中,您可以通过在查询中添加 sort 参数来做到这一点: sort=contact_again_time desc,created_at asc

    只要contact_again_time 出现,它就会按降序排序(并使用created_at 打破平局,这与您无关)。当只有created_at 存在时,它们将按升序排序。

    这应该直接转化为太阳黑子。

    更新:如果您想像sort=contact_again_time asc,created_at asc 一样排序,您将首先获得缺少contact_again_time 的文档,就像您在下面的评论中提到的那样。要将这些文档推送到最后,请在 Solr schema.xml 中将 sortMissingLast="true" 添加到 contact_again_time。如果created_at 在某些文档中也可能不存在,并且您希望获得相同的行为,则也应将sortMissingLast 添加到其中。

    【讨论】:

    • 我想说这几乎正是我正在寻找的答案。我刚刚遇到的唯一问题是我现在需要对第一个字段进行升序排序,因此在这种情况下将 nil 值排序在前面,这违背了 :(
    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多