如何用Sunspot突出显示单词?
我想在文本中突出显示已找到的单词,例如,如此处所示。
据我所知,我必须遵循以下步骤:
1)在我的模型中,我必须在我想要突出显示的字段中添加:stored => true
选项:
searchable do text :title, :stored => true text :description end
2)在我的控制器中,我必须声明我想要突出显示的字段:
def search @search = Article.search do keywords params[:search] do highlight :title end end end
3)在视图中我不知道该怎么做,我试过这个:
- @search.each_hit_with_result do |hit, result| %p= link_to raw(hit_title(hit)), article_path(result)
这是做方法hit_title
:
def hit_title(hit) if highlight = hit.highlight(:title) highlight.format { |word| "#{word}" } else h(hit.result.title) end end
但它没有按预期工作,它总是突出显示标题的第一个单词,即使搜索到的单词位于其末尾。
有更简单的方法吗?
我碰到了这个寻找解决方案来渲染来自轨道视图的太阳黑子搜索的亮点。
我在任何地方都找不到很多现成的解决方案,所以我使用了这篇文章的一部分来制作我的一个。 我对rails很新,所以这可能不完全是RoR方式。
就我而言,我在两个字段上进行了全文搜索,称之为notes
和description
。
为了能够向高亮显示html,我引入了一个值的哈希值,其中包含记录的id,列的名称及其突出显示的值,格式正确。 这允许我突出显示不同字段的搜索结果。
entry.rb:
searchable do text :description, :stored => true text :notes, :stored => true end
entries_controller.rb:
@search = Entry.search if params[:search].nil? || params[:search].empty? stext='' else stext=params[:search] end fulltext stext, :highlight => true paginate(page: params[:page], :per_page => 10) end @entries=@search.results @results=Hash.new @search.hits.each do |hit| hit.highlights(:description).each do |highlight| id=hit.primary_key.to_s.to_sym fr=highlight.format { |word| "#{word} " } @results.merge!(id => ["description",fr]) end hit.highlights(:notes).each do |highlight| id=hit.primary_key.to_s.to_sym fr=highlight.format { |word| "#{word} " } @results.merge!(id => ["notes",fr]) end end
在视图中,无论我想在哪里渲染任何值,我都会执行以下操作:
<% @entries.each do |f| %> <% j=f[:id].to_s.to_sym %> <% if !@results[j].nil? && @results[j][0]=="description" %> <%= @results[j][1].html_safe %> <% else %> <%= f[:description] %> <% end %> [...] (likewise for notes) <% end %>
请注意,我为
标记创建了一个css定义,以使文本显着。
代码看起来很好,突出了标题中的第一个匹配单词,因为我有类似的代码。 您是否尝试过重建solr索引并重新启动服务器?
此外,您可以尝试将solrconfig.xml还原为其默认值吗? 修改solrconfig.xml后有人遇到类似的问题,参考https://groups.google.com/forum/#!searchin/ruby-sunspot/highlight/ruby-sunspot/kHq0Dw35UWs/ANIUwERArTQJ
如果要覆盖solrconfig.xml中的突出显示选项,请在此站点http://outoftime.github.io/上搜索max_snippets。 您可能想尝试类似的选项
highlight :title, :max_snippets => 3, :fragment_size => 0 # 0 is infinite
你在使用子串搜索吗? 我在这里遇到了同样的问题,并意识到通过以下sunspot wiki教程启用子字符串匹配导致了问题。