t56k
t56k

Reputation: 6981

Rails: searching with pseudo-relevancy

I'm trying to write a search method that searches the full text of an Article and sorts the results by the number of occurrences of the search term in that full text. Something like this:

def search
  term = params[:term]
  @articles = Article.where("body like ?", "%#{term}%")
  @articles.each do |a|
    b = a.body.count(term)
  end
  @articles = @articles.order("#{b} desc").limit(10).pluck(:name)
  render json: @articles, b
end

The above obviously doesn't work, it's just there to explain the concept. Any ideas would be appreciated. Cheers!

Upvotes: 0

Views: 75

Answers (1)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

You'd be better off using a full-text search library to achieve this.

If you're using Postgres as your database, you can use pg_search which adds scopes to your models which make use of Postgres' build in full-text search functionality.

Alternatively if you don't want to add any external dependencies you can use Acts as Indexed to add ranked full-text results to your app.

A fairly comprehensive list of the various options can be found at Ruby Toolbox.

Disclosure: I'm the author of acts_as_indexed.

Upvotes: 1

Related Questions