ikeikeikeike's unk blog.

http://github-awards.com/users/ikeikeikeike

Railsでelasticsearchとsearchkick(retire)とacts-as-taggable-onでラクをしてfacetsした話

タグを付けてfacetsするところまで。コードは全く書きません。

便利でいいですね。

gem "searchkick"  # full text search
gem 'acts-as-taggable-on'  # For tags

インストール後migration実行

$ rake acts_as_taggable_on_engine:install:migrations
$ rake db:migrate

モデル定義

class Product < ActiveRecord::Base
  searchkick  # For full text search powerd by elasticsearch.
  acts_as_taggable  # Alias for acts_as_taggable_on :tags

  # for searchkick reindex data.
  #
  def search_data
    {
      hoge: hoge,
      homu: homu,
      home: home,
      tags: tag_list  # gen by acts_as_taggable_on.
    }
  end

end

Productにデータをテキトーに入れて, elasticsearchのindexを生成し直します(elasticsearchは事前に立ち上げておいてください)

Product.reindex

facetsしてみます

4.0.2@2.1.0 (main)> Product.search('*', limit: 0, fields: [:tags], facets: {tags: {limit: 5}}).facets
  Search (45.5ms)  {"query":{"match_all":{}},"size":0,"from":0,"facets":{"tags":{"terms":{"field":"tags","size":155}}},"fields":[]}
=> {"tags"=>
  {"_type"=>"terms",
   "missing"=>0,
   "total"=>3550,
   "other"=>2577,
   "terms"=>
    [{"term"=>"アメリカ", "count"=>269},
     {"term"=>"イギリス", "count"=>215},
     {"term"=>"日本", "count"=>182},
     {"term"=>"インド", "count"=>180},
     {"term"=>"ブラジル", "count"=>127}]}}

簡単すぎわらえない