I installed Searchkick and Elasticsearch for the first time.
I have the basics working and am trying to include the highlight feature.
The Index:
<%= form_tag books_path, method: :get do %>
<%= text_field_tag :q, nil %>
<% end %>
<div class="row">
<div class="col-md-8">
<% @books.each do |book| %>
<div class="media">
<div class="media-body">
<h4 class="media-heading">
<%= link_to book.title, book %>
</h4>
<small>
<%= book.description %>
</small></br>
<% if policy(book).edit? %>
<%= link_to 'Edit', edit_book_path(book) %>
<% end %>
</div>
</div>
<% end %>
<%= paginate @books %>
</div>
<div class="col-md-4">
<% if policy(Book.new).create? %>
<%= link_to "New Book", new_book_path, class: 'btn btn-success' %>
<% end %>
</div>
</div>
Controller
def index
query = params[:q].presence || "*"
@books = Book.search(query, field: [:title], highlight: {tag: "<strong>"})
authorize @books
end
Model
class Book < ActiveRecord::Base
require 'elasticsearch/model'
searchkick highlight: [:title, :description]
What am I missing?
I figured out how to highlight with Searchkick.
First, include searchkick in your model. Like so:
class Book < ActiveRecord::Base
searchkick highlight: [:description]
end
Second, include the highlight fields within your controller. I have a separate search controller for multiple models.
class SearchesController < ApplicationController
def index
@book_searches = Book.search(params[:query], operator: "or", fields: [:description], highlight: {tag: "<strong>", fields: {description: {fragment_size: 100}}})
@chapter_searches = Chapter.search(params[:query], operator: "or", fields: [:body], highlight: {tag: "<strong>", fields: {body: {fragment_size: 100}}})
end
end
Third, include the highlight feature in your search index view.
<% @book_searches.with_details.each do |book_search, details| %>
<% if book_search.class == Book %>
<h3><%= link_to book_search.title, [book_search] %></h3>
<p><%= simple_format details[:highlight][:description] %></p>
<% end %>
<% end %>
Don't forget to use with_details in your each loop.