ElasticsearchにRubyから接続してあれこれしたいっ!
2021年1月7日
Elasticsearchはすでにインストール済み(CentOS7でElasticsearchを使いたいっ!)で、起動もしてます。
elasticsearch(gem)をインストール
最終的にはGemfileに追加してbundle installする予定ですが、まずは動かしてみる。
gem install elasticsearch
indexの追加
indexは、ドキュメントを追加すると一緒に追加されるので明示的にindexだけを追加することはあまりないかもしれませんが
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
client.indices.create index: 'test'
indexの存在確認
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
result = client.indices.exists index: 'test'
puts result ? 'ある' : 'ない'
indexの削除
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
client.indices.delete index: 'test'
ドキュメントを追加してみる
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
client.create({
index: 'test',
type: 'foo',
id: 1,
body: {
name: '太郎'
}
})
ドキュメントを取得してみる
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
test = client.search({
index: 'test',
query: {
term: {
_id: 1
}
}
})
ドキュメントを更新してみる(1)
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
client.update_by_query({
index: 'test',
type: 'foo',
conflicts: 'proceed',
body: {
query: {
term: {
_id: 1
}
},
script: {
source: "ctx._source.name = '次郎'"
}
}
})
ドキュメントを更新してみる(2)
こっちのほうがシンプルかも。
require 'elasticsearch'
client = Elasticsearch::Client.new({log: true, url: 'localhost:9200' })
client.update_by_query({
index: 'test',
type: 'foo',
id: 1,
body: {
doc: {
name: '次郎'
}
}
})