如何使用ruby迭代这个json文档?
我有一个ruby代码块,如下所示:
require "elasticsearch" require "json" search_term = "big data" city = "Hong Kong" client = Elasticsearch::Client.new log: true r = client.search index: 'candidates', body: { query: { bool: { must: [ { match: { tags: search_term } }, { match: { city: city } } ] } } }
它会像这样产生多个回报:
{"_index":"candidates","_type":"data", "_id":"AU3DyAmvtewNSFHuYn88", "_score":3.889237, "_source":{"first":"Kota","last":"Okayama","city":"Tokyo","designation":"Systems Engineer","email":"user@hotmail.co.jp","phone":"phone","country":"Japan","industry":"Technology","tags":["remarks","virtualization big data"]}}
我想迭代它并提取各种元素。 我试过了
data = JSON.parse(r) data.each do |row| puts row["_source"]["first"] end
而错误是:
no implicit conversion of Hash into String (TypeError)
这个故事的最佳前进方向是什么?
我有解决方案,我希望它可以帮助别人。 我花了几个小时的小提琴和实验。 这里是:
require "elasticsearch" require "json" search_term = "big data" city = "Tokyo" client = Elasticsearch::Client.new log: true h = client.search index: 'swiss_candidates', body: { query: { bool: { must: [ { match: { tags: search_term } }, { match: { city: city } } ] } } } data = JSON.parse(h.to_json) data["hits"]["hits"].each do |r| puts r["_id"] puts r["_source"]["first"] puts r["_source"]["tags"][1] puts r["_source"]["screened"][0] end
重要的是将弹性搜索结果转换为ruby友好的东西。
JSON.parse
需要一个包含JSON文档的String
,但是你传递的是从client.search
返回的Hash
。
我不完全确定你要用它来实现什么,为什么你要将已经是Ruby Hash
东西解析为Ruby Hash
。
- 弹性搜索 – 实现“你是不是意味着”
- 使用rest-client ruby gem在elasticsearch get请求中传递json数据
- 使用Searchkick在ElasticSearch中搜索子文档
- 在Logstash中转换时间戳时区以获取输出索引名称
- Rails elasticsearch – 命名范围搜索
- URI :: InvalidURIError:方案http不接受注册表部分:: 9200(或错误的主机名?)
- 如何在新的Nitrous.io IDE上设置SearchKick / ElasticSearch?
- 如何使用elasticsearch / searchkick在我的导航栏上运行搜索栏并在特定页面中显示结果?