问题
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