如何用Sunspot突出显示找到的单词? [英] How highlight found word with Sunspot?

查看:82
本文介绍了如何用Sunspot突出显示找到的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我要突出显示文本中找到的单词,如此处所示.

I want to highlight found words in text, for example, as shown here.

据我所知,我必须执行以下步骤:

As far as I know I must follow these steps:

1)在我的模型中,必须在要突出显示的字段中添加:stored => true选项:

1) In my model, I must add :stored => true option to the field which I want to highlight:

searchable do 
    text :title, :stored => true
    text :description
end

2)在我的控制器中,我必须声明要突出显示的字段:

2) In my controller, I have to declare which field I want highlighted:

def search
    @search = Article.search do
        keywords params[:search] do
            highlight :title
        end
    end
end

3)在我不确定该怎么做的情况下,我尝试了此操作:

3) In the view I'm not sure what to do, I tried this:

- @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| "<font color='green'>#{word}</font>" }
    else
        h(hit.result.title)
    end
end

但是它不能按预期方式工作,即使搜索到的单词位于标题的最后,它仍会突出显示标题的第一个单词.

But it doesn't work as expected, it always highlights the first word of the title, even if the searched word is at the end of it.

有没有更简单的方法可以做到这一点?

Is there an easier way to do this?

推荐答案

代码突出显示标题中的第一个匹配词对我来说很好,因为我有类似的代码.您是否尝试过重建Solr索引并重新启动服务器?

Code looks good to me for highlighting the first matching word in the title, since I have similar code. Have you tried rebuilding your solr index and restarting the servers?

还可以尝试将solrconfig.xml还原为其默认值吗?修改solrconfig.xml后,有人遇到了类似的问题,请参阅

Also, can you try reverting your solrconfig.xml to its default values? Someone had a similar problem after modifying solrconfig.xml, Ref https://groups.google.com/forum/#!searchin/ruby-sunspot/highlight/ruby-sunspot/kHq0Dw35UWs/ANIUwERArTQJ

如果要覆盖solrconfig.xml中的突出显示选项,请在此站点 http://outoftime中搜索max_snippets. github.io/.您可能想尝试类似

If you want to override the highlighting option in solrconfig.xml, search for max_snippets on this site http://outoftime.github.io/ . You may want to try options like

highlight :title, :max_snippets => 3, :fragment_size => 0  # 0 is infinite

这篇关于如何用Sunspot突出显示找到的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆