Search code examples
rubyrestelasticsearchrest-client

Calling Elasticsearch Rest API from Ruby script


Im new to Elasticsearch and Ruby script, Please help me in resolving this. I want add/remove aliases from index everyday by cron job.

I tried using shell script as below and its working as expected

curl -XPOST "http://$es_host:9200/_aliases" -d "$json"

Ruby Script

#! /usr/bin/env ruby
require 'rubygems'
require 'json'
require 'rest_client'

target="http://localhost:9200/_aliases"

request = RestClient::Request.new(
        :method => :post,
        :url => target,
        :payload => input)
puts request.execute

input is valid json(i tested it). but Ruby script throwing below error.

> ruby-1.9.3-p374@11.4.0-1/gems/rest-client-1.6.7/lib/restclient/abstract_response.rb:48:in `return!': 400 Bad Request (RestClient::BadRequest)     from
> /.rvm/gems/ruby-1.9.3-p374@11.4.0-1/gems/rest-client-1.6.7/lib/restclient/request.rb:230:in `process_result'  from
> /.rvm/gems/ruby-1.9.3-p374@11.4.0-1/gems/rest-client-1.6.7/lib/restclient/request.rb:178:in `block in transmit'   from
> /.rvm/rubies/ruby-1.9.3-p374/lib/ruby/1.9.1/net/http.rb:745:in
> `start'   from
> /.rvm/gems/ruby-1.9.3-p374@11.4.0-1/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit'    from
> /.rvm/gems/ruby-1.9.3-p374@11.4.0-1/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in
> `execute'     from es_alias.rb:56:in `<main>'

P.S - Ruby script printing all aliases if I just remove payload and try.


Solution

  • I just started using elasticsearch ruby client and its solved the purpose and its better to use elasticsearch ruby client to do operations in elasticsearch because ruby client provides connection pooling (connecting through multiple elasticsearch nodes)

    http://www.rubydoc.info/gems/elasticsearch-api/Elasticsearch