ruby-on-rails-3 - 在RestClient中解析elasticsearch响应

标签 ruby-on-rails-3 json datamapper elasticsearch rest-client

我正在使用Datamapper作为ORM编写Rails 3应用程序。我正在寻找使用ElasticSearch进行搜索的方法,但由于它似乎依赖ActiveRecord,因此无法使用Tire gem 。

我正在使用RestClient将请求提交到ElasticSearch,但是在解析响应时却遇到了麻烦。

如果提交GET请求“http://localhost:9200/twitter/tweet/2”,则在浏览器中得到以下内容:

{
  "_index": "twitter",
  "_type": "tweet",
  "_id": "2",
  "_version": 3,
  "exists": true,
  "_source": {
    "user": "kimchy",
    "post_date": "2009-11-15T14:12:12",
    "message": "kimchy kimchy says"
  }
}

在Rails中,当我输入以下内容时:
response = RestClient.get 'http://localhost:9200/twitter/tweet/2',{:content_type => :json, :accept => :json}

我得到这个结果:
{
  "_index": "twitter",
  "_type": "tweet",
  "_id": "2",
  "_version": 3,
  "exists": true,
  "_source": {
    "user": "kimchy",
    "post_date": "2009-11-15T14:12:12",
    "message": "kimchy kimchy says"
  }
}

这看起来是正确的,但是我无法像通常使用JSON那样使用点符号来获取数据。

例如,由于出现未定义的方法错误,我无法编写response._type

非常感谢您的帮助!

最佳答案

如果要进行手动转换,则可以解析json的响应,然后将其手动转换为对象以使用点符号访问字段。

像这样:

require 'json'
require 'ostruct'

response = RestClient.get '...url...'
o = OpenStruct.new(JSON.parse(response))

然后,您应该可以使用o._typeo.message访问字段。

关于ruby-on-rails-3 - 在RestClient中解析elasticsearch响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10430303/

相关文章:

ruby-on-rails - 无法为 ActionMailer::Base 找到 Rails 3 "The action ' 方法'

javascript - 如何为 Object.define() 定义的属性创建唯一的 toJSON 方法

mysql - Ruby DataObjects::SQLError 查询不包含字符串参数

java - 发送带有两个方法的返回值的 JSON 响应

sqlite - 将 sqlite 用于低流量 Web 应用程序是否合理?

couchdb - Merb、DataMapper 和 CouchDB(或 MongoDB)的 Multi-Tenancy

ruby-on-rails - 在 Rails 中创建新环境

ruby-on-rails - rake 数据库 :schema:load vs. 迁移

ruby-on-rails - Ruby on Rails Instagram Gem 点赞和评论计数无法正常工作

xml - spring mvc 休息响应 json 和 xml