5

I'm trying to perform a search, order the results randomly, and only return a number of results, not all matches. Something like limit(2) I've tried using the Solr param 'rows' but that doesn't seem to do anything:

@featured_articles = Article.search do 
  with(:is_featured, true)
  order_by :random
  adjust_solr_params do |params|
    params[:rows] = 2
  end
end

@featured_articles.total should be 2, but it returns more than 2

How can I get a randomized fixed number of results?

condit
  • 10,852
  • 2
  • 41
  • 60
gt565k
  • 7,755
  • 3
  • 16
  • 9

2 Answers2

1

Rather than adjusting params, just add a line:

order_by :random
rows :2

See here: http://wiki.apache.org/solr/CommonQueryParameters

Ryan Clark
  • 764
  • 1
  • 8
  • 29
0

All ruby example..

@featured_articles = Article.search do 
  with(:is_featured, true)
  order_by :random
end.shuffle.take(2)

If you don't need Solr, depending on your db, you could also do: Article.where(is_featured: true).order("RANDOM()").limit(2)

wrdevos
  • 2,029
  • 16
  • 19