gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 23:06:23 24 4
gpt4 key购买 nike

我正在使用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com