一尘不染

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

解决这些难题的最佳方法是什么?


阅读 286

收藏
2020-06-22

共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

重要的事情似乎是将elasticsearch结果转换为红宝石友好的东西。

2020-06-22