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

血红的双手。 提交于 2020-01-02 08:08:54

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12988201/passing-json-data-in-elasticsearch-get-request-using-rest-client-ruby-gem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!