Setting up Facets in Elasticsearch with Searchkick gem in Rails 4.1

前端 未结 1 1721
不思量自难忘°
不思量自难忘° 2020-12-30 17:33

I want the users to be able to easily find a series so want to set up facets. I have followed the directions at seachkick and everything is working fine, but when I setup Fa

相关标签:
1条回答
  • 2020-12-30 18:21

    I finally got it working by doing the following. Not sure if it is the best method but it works! Hope it helps and if you have improvements or suggestions feel free to let me know.

    # app/models/movie.rb
    def self.facets_search(params)
      query = params[:query].presence || "*"
      conditions = {}
      conditions[:year] = params[:year] if params[:year].present?
    
      movies = Movie.search query, where: conditions, 
        facets: [:year], 
        smart_facets: true, page: params[:page], suggest: true, highlight: true,
        per_page: 10
      movies
    end
    

    .

    # app/controllers/movies_controller.rb
    def index
      @movies = Movie.facets_search(params)
    end
    

    .

    # app/views/movies/index.html.erb
    <% if @movies.facets["year"]["terms"].present? %>
        <div>
            <ul>
            <% @movies.facets["year"]["terms"].each do |filter| %>
              <li><%= link_to "#{filter["term"]} (#{filter["count"]})", "/movies?year=#{filter["term"]}" %></li>
            <% end %>
            </ul>
        </div>
    <% end %>
    
    0 讨论(0)
提交回复
热议问题