使用rest-client ruby​​ gem在elasticsearch get请求中传递json数据

如何使用rest client执行以下查询(在doc中给出)。

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

我试过这样做:

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

这引发了一个错误:

 in `process_url_params': undefined method `delete_if' for # (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 `' 

当我使用RestClient.post做同样的RestClient.post ,它给了我正确的结果! 但是elasticsearch doc在curl命令中使用XGET进行搜索查询而不是XPOST 。 如何使RestClient.get方法起作用?

如果有其他/更好的方法来执行此操作,请建议。

RestClient无法使用GET发送请求主体。 你有两个选择:

将您的查询作为source URL参数传递:

 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 

……或者只是使用POST


更新:修复了URL参数的错误传递,注意params哈希。

万一其他人发现这个。 虽然不推荐,但可以通过使用主API用于创建调用的内部Request方法向GET发送请求主体。

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

有关详细信息,请参见此处