I'm implementing a full text search with sunspot, in which i store the text fields in order to get highlighted results.
Model code:
searchable do
text :name, :stored => true, :boost => 5.0
text :body, :stored => true, :boost => 3.0
# ... some other non-text fields
end
controller code:
@search = Model.search do
fulltext searchtext, highlight: true # searchtext comes from params
# ... some other fields
end
Rendering
@search.hits.each do |hit|
hit.highlights(:name).each do |h|
result = h.format { |word| "<result>#{word}</result>" }
# output the result
end
hit.highlights(:body).each do |h|
result = h.format { |word| "<result>#{word}</result>" }
# output the result
end
end
Everything works beautifully, except that when I am rendering the highlighted hit, I only get one fragment of the actual text.
So, instead of getting the phrase (which might be long), I only get a fragment of it. I've been trying around to put :fragment_size in the search definition (controller) but to no avail.
Any suggestion on how to output the FULL (:name or :body) and not just a fragment of it with highlight -> hit?
Thanks in advance.
I found a workaround, but even if it works fine, I believe there should be some other way, so I'm still expecting some answers, if you please.
My workaround goes as follows:
I remove the markups I placed in my highlighted hit into a new variable:
a=result.gsub(/<\/?result>/,"")
fetch the corresponding field with Active Record
model=Model.find(hit.primary_key)
and replace the unformatted text (variable a
) with the formatted (variable result
)
newresult=model.body.gsub(a,result)
thus resulting to the desired outcome.