How to use sunspot_rails gem to search for related articles

徘徊边缘 提交于 2019-12-09 02:21:53

问题


I have a mini blog app and i would like user to view articles that relates to what they are reading in the article show page. without the sunspot_rails gem i would do something like this

in my model

  def self.related_search(query, join = "AND")
    find(:all, :conditions => related_search_conditions(query, join))
  end

  def self.related_search_conditions(query, join)
    query.split(/\s+/).map do |word|
      '(' + %w[name description notes].map { |col| "#{col} LIKE #{sanitize('%' + word.to_s + '%')}" }.join(' OR ') + ')'
    end.join(" #{join} ")
  end

then in my view it would be like this

@article.related_search

but i want to use the sunspot_rails gem to make this way easy. Any help. Thanks


回答1:


As RocketR mentions, this is a trivial use case for Sunspot.

First, use Sunspot to specify that you have three fields to be indexed as text.

class Article < ActiveRecord::Base
  searchable do
    text :name
    text :description
    text :notes
  end
end

Then issue a search, likely from within a controller action. The @search object below contains metadata about the search response, including the matching objects under its results method.

@search = Article.search do
  keywords query
end
@results = @search.results

To find other documents that are similar to an object you already have loaded, say in a show action, you can call the more_like_this instance method. This is a special kind of search, which uses Solr's "More Like This" functionality, and which returns a search object similar to the above full-text search. You can use its results method to render the results of that search.

<%= render @article.more_like_this.results %>

The more_like_this method also accepts a block with similar options to the search block, so you can have more control over how you're judging similarity.

Hope that helps!



来源:https://stackoverflow.com/questions/7086092/how-to-use-sunspot-rails-gem-to-search-for-related-articles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!