简体   繁体   English

通过Searchkick和Elasticsearch突出显示

[英]Highlight with Searchkick and Elasticsearch

I installed Searchkick and Elasticsearch for the first time. 我是第一次安装Searchkick和Elasticsearch。

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. 我想出了如何用Searchkick突出显示。

First, include searchkick in your model. 首先,在模型中包含searchkick。 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. 不要忘记在每个循环中使用with_details。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM