4

我希望用戶能夠輕鬆找到想要設置構面的系列。我遵循seachkick的指示,一切工作正常,但是當我設置Facets時,我將以下內容作爲回報。我希望它能像他們的文檔一樣。希望有人能幫忙。在Rails 4.1中使用Searchkick gem在Elasticsearch中設置構面

我得到這個myapp.com/movies

{ 
    "name"=> { 
    "_type"=> "terms", 
    "missing"=> 0, 
    "total"=> 1, 
    "other"=> 0, 
    "terms"=> [ 
     { 
     "term"=> "Bloop", 
     "count"=> 1 
     } 
    ] 
    }, 
    "imdb"=> { 
    "_type"=> "terms", 
    "missing"=> 0, 
    "total"=> 1, 
    "other"=> 0, 
    "terms"=> [ 
     { 
     "term" => "http://www.bloop.com", 
     "count" => 1 
     } 
    ] 
    } 
} 

#app/views/movies/index.html.erb 
<%= p @series.facets %> 

#app/controllers/movies_controller.rb 
def index 
    query = params[:query].presence || "*" 
    @movies = Movie.search(query, page: params[:page], 
           suggest: true, 
           per_page: 20, 
           facets: [:name, :imdb]) 
end 

#db/schema.rb 
create_table "movies", force: true do |t| 
    t.string "name" 
    t.text  "description" 
    t.string "imdb" 
    t.string "year" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
end 

回答

8

我終於得到它通過執行以下工作。不知道它是否是最好的方法,但它的工作原理!希望它有幫助,如果你有改進或建議,請隨時讓我知道。

# 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 %> 
+1

謝謝你:) – wyclin

+0

@crentist如果選擇了facet,你將如何維護'query'? – cman77

相關問題