ruby
  • elasticsearch
  • rest-client
  • 2012-10-20 19 views 3 likes 
    3

    如何使用rest客戶端執行以下查詢(在doc中給出)。在elasticsearch中傳遞json數據使用rest-client ruby​​獲取請求gem

    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 #<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>' 
    

    當我使用RestClient.post一樣的,它給了我正確的結果!但elasticsearch文檔在curl命令中使用XGET作爲搜索查詢,而不是XPOST。如何獲得RestClient.get方法?

    如果有更多/更好的方法來做這個動作,請建議。

    +0

    我認爲這與get或post沒有任何關係,但是使用'''get_check2.rb'''中的代碼。使用RestClient從ES獲得的實際響應是什麼?這可能是你處理錯誤的方式! – phoet

    +0

    即使使用POST請求,Elasticsearch查詢似乎也能正常工作。所以我們可以使用簡單的休息客戶端。 –

    回答

    5

    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


    UPDATE:固定的URL參數不正確的傳球,注意params哈希。

    +0

    Coffescript似乎也不支持GET Body。 – EnabrenTane

    1

    萬一其他人發現此情況。雖然不推薦,但可以通過使用主API用於創建它的調用的內部請求方法來向GET請求主體發送請求。

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

    有關更多詳細信息,請參見here

    相關問題