如何使用ruby来遍历这个json文件? [英] how can I iterate through this json document using ruby?

查看:128
本文介绍了如何使用ruby来遍历这个json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个红宝石代码块,如下所示:

I have a ruby code block, as follows:

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
          }
        }
      ]
    }
  }
} 

它会产生如下这样的多个返回:

It produces multiple returns like this one:

{"_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"]}}

我想迭代它并提取各种元素。我试过

I want to iterate through it and extract various elements. I have tried

 data = JSON.parse(r)
  data.each do |row|
  puts row["_source"]["first"]
 end

并且错误是:

no implicit conversion of Hash into String (TypeError)

这个故事最好的方法是什么?

What's the best way forward on this chaps?

推荐答案

p>我有解决方案,希望它能帮助别人。花了我几个小时的时间和实验。这里是:

I have the solution, I hope it helps somebody else. It took me hours of fiddling and experimentation. Here it is:

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

重要的事情似乎是将弹性搜索结果转换为红宝石友善的东西。

The important thing seems to be to convert the elasticsearch result into something ruby friendly.

这篇关于如何使用ruby来遍历这个json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆