如何使用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