如何使用sunspot_rails gem 搜索相关文章
我有一个迷你博客应用程序,我希望用户查看与他们在文章显示页面中阅读的内容相关的文章。 做类似的事情
如果没有 sunspot_rails gem,我会在我的模型中
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
,然后在我看来,它会像这样,
@article.related_search
但我想使用 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 RocketR 提到的,这是 Sunspot 的一个简单用例。
首先,使用 Sunspot 指定将三个字段作为文本索引。
然后可能从控制器操作中发出搜索。下面的
@search
对象包含有关搜索响应的元数据,包括其results
方法下的匹配对象。要查找与已加载的对象类似的其他文档(例如在
show
操作中),您可以调用more_like_this
实例方法。这是一种特殊的搜索,它使用 Solr 的“More Like This”功能,并返回与上面的全文搜索类似的搜索对象。您可以使用其results
方法来呈现该搜索的结果。more_like_this 方法也接受具有类似的块搜索块的选项,以便您可以更好地控制如何判断相似性。
希望有帮助!
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.
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 itsresults
method.To find other documents that are similar to an object you already have loaded, say in a
show
action, you can call themore_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 itsresults
method to render the results of that search.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!