如何使用ruby迭代这个json文档?

时间:2015-06-06 07:55:00

标签: ruby json elasticsearch

我有一个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)

这个故事的最佳前进方向是什么?

2 个答案:

答案 0 :(得分:1)

我有解决方案,我希望它可以帮助其他人。我花了几个小时的小提琴和实验。这是:

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

重要的是将弹性搜索结果转换为红宝石友好的东西。

答案 1 :(得分:0)

JSON.parse期望包含JSON文档的String,但您传递的是从Hash返回的client.search

我不完全确定你想要实现的目标,为什么你要将已经是Ruby Hash的东西解析为Ruby Hash