22
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rsolrを使う

Last updated at Posted at 2013-03-03

RubyからSolrを使うためのライブラリrsolrの使い方覚え書き
solr-rubyというのも見つけたけど、Solr4.1では使えないみたい

####インストール

$ gem install rsolr

Solrのインストール手順は省略、設定はデフォルトのまま

####使ってみる

rsolr_sample.rb
require 'rubygems'
require 'rsolr'

url = "http://localhost:8983/solr"
solr = RSolr.connect :url => url

solr.add :id => 1234, :name => "rsolr sample", :price => 100
solr.commit #commitしないとインデックスに反映されないので注意

contents = (0..10).map do |id|
    {:id => id, :name => "sample-#{id}", :price => id * 100}
end

solr.add contents
solr.optimize
solr.commit

#デフォルトだと結果はHashで返ってくる
#:wt => json 等の指定でjsonやxmlでの取得も可能
res = solr.get 'select', :params => {:q=>'*:*', :start => 5, :rows => 5}

puts "get contents: #{res['response']['numFound']}"
res['response']['docs'].each do |doc|
    puts "#{doc['name']} #{doc['price']}"
end

solr.delete_by_id 1234
solr.delete_by_query 'name:"sample-5"'
solr.commit

res = solr.get 'select', :params => {:q=>'*:*'}
puts "get contents: #{res['response']['numFound']}"
res['response']['docs'].each do |doc|
    puts "#{doc['name']} #{doc['price']}"
end

####結果

$ ruby rsolr_sample.rb
get contents: 12
sample-5 500.0
sample-6 600.0
sample-7 700.0
sample-8 800.0
sample-9 900.0
get contents: 10
sample-0 0.0
sample-1 100.0
sample-2 200.0
sample-3 300.0
sample-4 400.0
sample-6 600.0
sample-7 700.0
sample-8 800.0
sample-9 900.0
sample-10 1000.0

簡単ですね

22
26
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
22
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?