简体   繁体   English

如何使用 sunspot_rails gem 搜索相关文章

[英]How to use sunspot_rails gem to search for related articles

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如果没有 sunspot_rails gem,我会做这样的事情

in my model在我的 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.但我想使用 sunspot_rails gem 来简化这种方式。 Any help.任何帮助。 Thanks谢谢

As RocketR mentions, this is a trivial use case for Sunspot.正如 RocketR 所提到的,这是 Sunspot 的一个微不足道的用例。

First, use Sunspot to specify that you have three fields to be indexed as text.首先,使用 Sunspot 指定您有三个要作为文本索引的字段。

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

Then issue a search, likely from within a controller action.然后发出搜索,可能来自 controller 操作。 The @search object below contains metadata about the search response, including the matching objects under its results method.下面的@search object 包含有关搜索响应的元数据,包括其results方法下的匹配对象。

@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.要查找与您已经加载的 object 类似的其他文档,例如在show操作中,您可以调用more_like_this实例方法。 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.这是一种特殊的搜索,它使用 Solr 的“More Like This”功能,并返回类似于上述全文搜索的搜索 object。 You can use its results method to render the results of that search.您可以使用它的results方法来呈现该搜索的结果。

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

Themore_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. more_like_this方法还接受与搜索块具有相似选项的块,因此您可以更好地控制判断相似性的方式。

Hope that helps!希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM