How to highlight a found word using Sunspot?

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

As far as I know, I should follow these steps:

1) In my model, I have to add a parameter :stored => trueto the field that I want to highlight:

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

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

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

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)

This is what the method does 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 does not work as expected, it always highlights the first word of the title, even if the search word is at the end of it.

Is there an easier way to do this?

+5
source share
3

.

, , . , RoR.

, notes description.

html , , , , . .

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| "<result>#{word}</result>" }
        @results.merge!(id => ["description",fr])
    end
    hit.highlights(:notes).each do |highlight|
        id=hit.primary_key.to_s.to_sym
        fr=highlight.format { |word| "<result>#{word}</result>" }
        @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 <result>, .

+1

, , . solr ?

solrconfig.xml ? - solrconfig.xml, Ref https://groups.google.com/forum/#!searchin/ruby-sunspot/highlight/ruby-sunspot/kHq0Dw35UWs/ANIUwERArTQJ

solrconfig.xml, max_snippets http://outoftime.imtqy.com/. ,

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

Do you use substring search? I have the same problem, and I realized that including the substring in the match using the sunspot wiki tutorial led to this problem.

0
source

All Articles