ruby-on-railssolrsunspot-rails

Solr (Sunspot) conditional order_by


I use Solr sunspot gem in my Rails app. What I have now: order_by(:some_time, :desc). What I need to do is:

If :some time column value is within last hour then all records with this condition are ordered by :status column otherwise ordered by :some_time

I didn't find anything similar in the docs and I am not sure what is a good way to implement this.

PS: I tried to do grouping and ordering after solr search is finished, but it looks heavy and I believe things should be consistent, so if there is any chance to do it with solr, I would like to go for it.


Solution

  • The sunspot gem will let you say order_by_function to use Solr's functional ordering ability (look for "Search by Function"). So it looks to me like you could do this or something like it (not tested):

    order_by_function(:map, [:ms, [:NOW, :some_date], '0', '3600000', '0'], :status)
    

    In other words: find the age in milliseconds of the document, and anything within 1 hour "flatten" to 0 (so they are all tied). Break ties by sorting by status. Seems like that should work, right?