LoginSignup
5
5

More than 5 years have passed since last update.

RubyからSolrのTermsComponentを利用する

Posted at

RubyからSolrのTermsComponentを利用する

利用するライブラリ

Solrへのアクセスする際に使用するライブラリとして、rsolrを使用します。

TermsComponentとは?

検索フィールドでの単語の出現数を返すSolrのComponent。

cf. http://wiki.apache.org/solr/TermsComponent

検索部分の実装

まず、TermsComponentへリクエストを投げる部分の処理を実装します。

require 'rsolr-ext'
class TermSearch
  class << self
    def search(solr_url, terms_params = {})
      solr = RSolr::Ext.connect url: solr_url
      params = build_params(terms_params)
      # #{solr_url}/terms へアクセスする
      response = solr.get 'terms', params: params
      parse_term_response(response)
    end

  private
    #
    # TermsComponent用のクエリーに変換する
    # @return [Hash]
    def build_params(terms_params)
      options = {}
      terms_params.each do |k, v|
        options["terms.#{k}"] = v
      end
      options
    end

    #
    # SolrのレスポンスをHashに変換する
    # @return [Hash]
    def parse_term_response(response)
      terms = {}
      return terms unless response['terms']
      response['terms'].collect { |(terms_area_field, values_and_hits)|
        items = {}
        values_and_hits.each_slice(2) do |k, v|
          items[k] = v
        end
        terms[terms_area_field] = items
      }
      terms
    end
  end
end

実際のリクエストを投げてみる

上記の実装を利用して、prefectureのフィールドでの単語の出現回数を取得してみます。
(注)検索対象のフィールドは、Solrのスキーマに合わせて、変更して下さい。

# prefectureのfieldでの出現回数の上位5件を取得する。
TermSearch.search("<SolrのURL>", {fl: 'prefecture', limit: 5})
D, [2014-05-22T16:16:26.358840 #18818] DEBUG -- :   SOLR Request (19.7ms)  [ path=terms parameters={terms.fl: ["prefecture_ja", "area_ja"], terms.limit: 10} ]
=> {
    "prefecture" => {
         "東京都" => 22,
        "鹿児島県" => 2,
         "三重県" => 1,
         "千葉県" => 1,
         "宮城県" => 1
    }
}

複数のフィールドで、検索を行う場合は、下記のように検索対象のフィールドを配列で指定します。

# prefectureのfieldでの出現回数の上位5件を取得する。
TermSearch.search("<SolrのURL>", {fl: ['prefecture','area'], limit: 5})
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5