[001] 使用 Ruby elasticsearch 7.14 获取集群状态
总结
使用Ruby的Elasticsearch客户端来操作Elasticsearch 7.14的REST API。同时,为了比较,也附上了在Kibana DevTool中的查询。
这次我们将进行”获取集群状态”的操作。
验证环境
使用Elasticsearch + Kibana (7.14)进行了以下验证数据“Shakespeare”的注册。
[00] 使用 Ruby 的 Elasticsearch 客户端包操作 Elasticsearch 7.14 进行验证环境的构建。
参考来源
实践 (shí
如果是Kibana DevTool的情况下
程式碼
GET _cluster/health
最终的结果。

在Ruby的情况下
代码 (Mandarin: “daima”)
重要的部分是「if __FILE__ == $0 之後」。
只需要一个选项,以下是对该句子的汉语本地化改写:
对于类MySimpleClient,可以完全复制(但在此之前,应根据需要重新解析192.168.10.115)。
#!/usr/bin/env ruby
# -*- encoding: utf-8 -*-
require 'multi_json'
require 'faraday'
require 'elasticsearch/api'
require 'active_support/core_ext' #! note_0004
require 'active_support' #! note_0005
class MySimpleClient
# note_0001
include Elasticsearch::API
CONNECTION = ::Faraday::Connection.new url: 'http://192.168.10.115:29200'
def perform_request(method, path, params, body, headers = nil)
#! note_0003
CONNECTION.run_request \
method.downcase.to_sym,
path_with_params(path, params),
(body ? MultiJson.dump(body): nil),
{'Content-Type' => 'application/json'}
end
private
def path_with_params(path, params)
return path if params.blank?
case params
when String
"#{path}?#{params}"
when Hash
"#{path}?#{params.to_query}"
else
raise ArgumentError, "Cannot parse params: '#{params}'"
end
end
end
if __FILE__ == $0
client = MySimpleClient.new
res = client.cluster.health #! note_0002
h = JSON.parse(res)
pp h
end
# note_0001: https://rubydoc.info/gems/elasticsearch-api
# note_0002: https://rubydoc.info/gems/elasticsearch-api/Elasticsearch/API/Cluster/Actions#health-instance_method
# note_0003: client.cluster.health から呼び出されるので実装が必要である
# note_0004: 'active_support' を 'active_support/core_ext' に変更する.
# APIドキュメントにある 'active_support' 指定だと次のエラーが発生してしまうためである.
# tutorial.rb:26:in `path_with_params': undefined method `blank?' for {}:Hash (NoMethodError)
# note_0005: require 'active_support' が存在しないと次のエラーが発生してしまう.
# /usr/local/bundle/gems/activesupport-6.0.4/lib/active_support/core_ext/object/json.rb:42:
# in `to_json': uninitialized constant ActiveSupport::JSON (NameError)
最终结果
{"cluster_name"=>"docker-cluster",
"status"=>"yellow",
"timed_out"=>false,
"number_of_nodes"=>1,
"number_of_data_nodes"=>1,
"active_primary_shards"=>18,
"active_shards"=>18,
"relocating_shards"=>0,
"initializing_shards"=>0,
"unassigned_shards"=>3,
"delayed_unassigned_shards"=>0,
"number_of_pending_tasks"=>0,
"number_of_in_flight_fetch"=>0,
"task_max_waiting_in_queue_millis"=>0,
"active_shards_percent_as_number"=>85.71428571428571}
验证
DevTool与Ruby的结果是否一致?
?看起来是一致的
