如何使用 sunspot_rails gem 搜索相关文章 [英] How to use sunspot_rails gem to search for related articles
问题描述
我有一个迷你博客应用程序,我希望用户在文章显示页面中查看与他们正在阅读的内容相关的文章.如果没有 sunspot_rails gem,我会做这样的事情
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
在我的模型中
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
但我想使用 sunspot_rails gem 来简化这种方式.任何帮助.谢谢
but i want to use the sunspot_rails gem to make this way easy. Any help. Thanks
推荐答案
正如 RocketR 所提到的,这是 Sunspot 的一个微不足道的用例.
As RocketR mentions, this is a trivial use case for Sunspot.
首先,使用 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
然后发出搜索,可能是在控制器操作中.下面的 @search
对象包含有关搜索响应的元数据,包括其 results
方法下的匹配对象.
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
要查找与您已加载的对象相似的其他文档,例如在 show
操作中,您可以调用 more_like_this
实例方法.这是一种特殊的搜索,它使用 Solr 的More Like This"功能,并返回一个类似于上述全文搜索的搜索对象.您可以使用其 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 %>
more_like_this 方法也接受一个块具有与搜索块相似的选项,因此您可以更好地控制判断相似性的方式.
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.
希望有帮助!
这篇关于如何使用 sunspot_rails gem 搜索相关文章的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!