passing json data in elasticsearch get request using rest-client ruby gem
Asked Answered
P

2

4

How do I execute the below query(given in doc) using rest client.

curl -XGET 'http://localhost:9200/twitter/tweet/_search' -d '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}
'

I tried doing this:

q = '{
    "query" : {
        "term" : { "user" : "kimchy" }
    }
}
'

r = JSON.parse(RestClient.get('http://localhost:9200/twitter/tweet/_search', q))

This threw up an error:

in `process_url_params': undefined method `delete_if' for #<String:0x8b12e18>     (NoMethodError)
    from /home/socialapps/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:40:in `initialize'
    from /home/socialapps/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `new'
    from /home/socialapps/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
    from /home/socialapps/.rvm/gems/ruby-1.9.3-p194/gems/rest-client-1.6.7/lib/restclient.rb:68:in `get'
    from get_check2.rb:12:in `<main>'

When I do the same using RestClient.post, it gives me the right results!. But the elasticsearch doc uses XGET in curl command for the search query and not XPOST. How do I get the RestClient.get method to work?

If there are alternate/better ways of doing this action, please suggest.

Pneumatograph answered 20/10, 2012 at 11:59 Comment(2)
i think that this has nothing to do with get or post but with the code you have in get_check2.rb. what is the actual response that you get from ES using RestClient? it's probably something that you handling the wrong way!Chromophore
Elasticsearch queries seems to work just fine even you use a POST request. So we can use a simple rest client.Unpleasantness
H
5

RestClient can't send request bodies with GET. You've got two options:

Pass your query as the source URL parameter:

require 'rest_client'
require 'json'

# RestClient.log=STDOUT # Optionally turn on logging

q = '{
    "query" : { "term" : { "user" : "kimchy" } }
}
'
r = JSON.parse \
      RestClient.get( 'http://localhost:9200/twitter/tweet/_search',
                      params: { source: q } )

puts r

...or just use POST.


UPDATE: Fixed incorrect passing of the URL parameter, notice the params Hash.

Hewett answered 20/10, 2012 at 17:16 Comment(1)
Coffescript doesn't seem to support GET Bodies either.Reverence
S
1

In case anyone else finds this. It IS possible, although not recommended, to send request bodies with GET by using the internal Request method that the main API uses to create it's calls.

RestClient::Request.execute( method: :get, 
                             url: 'http://localhost:9200/twitter/tweet/_search',
                             payload: {source: q} )

See here for more details.

Spectra answered 31/8, 2014 at 6:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.