我正在尝试将数据从mongodb提取到Elasticsearch,getMongodoc = coll.find().limit(10)
将在mongo中找到前10个条目。
如您所见,result = ec.mongoConn
应该从类mongoConn()
中的方法MongoConnector
获得结果。当我使用p hsh
(检查输出是否正确)时,它将打印10个entires,而p result = ec.mongoConn
将打印#<Enumerator: #<Mongo::Cursor:0x70284070232580 @view=#<Mongo::Collection::View:0x70284066032180 namespace='mydatabase.mycollection' @filter={} @options={"limit"=>10}>>:each>
我将p hsh
更改为return hsh
,p result = ec.mongoConn
将获得正确的结果,但它只打印第一个条目而不是所有10个条目。似乎hsh
的值没有正确传递给result = ec.mongoConn
,有谁能告诉我我做错了什么?这是因为我在方法调用方面做错了吗?
class MongoConncetor
def mongoConn()
BSON::OrderedHash.new
client = Mongo::Client.new([ 'xx.xx.xx.xx:27017' ], :database => 'mydatabase')
coll = client[:mycollection]
getMongodoc = coll.find().limit(10)
getMongodoc.each do |document|
hsh = symbolize_keys(document.to_hash).select { |hsh| hsh != :_id }
return hsh
# p hsh
end
end
class ElasticConnector < MongoConncetor
include Elasticsearch::API
CONNECTION = ::Faraday::Connection.new url: 'http://localhost:9200'
def perform_request(method, path, params, body)
puts "--> #{method.upcase} #{path} #{params} #{body}"
CONNECTION.run_request \
method.downcase.to_sym,
path,
((
body ? MultiJson.dump(body) : nil)),
{'Content-Type' => 'application/json'}
end
ec = ElasticConnector.new
p result = ec.mongoConn
client = ElasticConnector.new
client.bulk index: 'myindex',
type:'test' ,
body: result
end
答案 0 :(得分:1)
您正在循环中调用return(each
)。这将停止循环并返回第一个结果。尝试类似:
getMongodoc.map do |document|
symbolize_keys(document.to_hash).select { |hsh| hsh != :_id }
end
注意:
更新:
[{}, {}, ...]
list_of_results = get_mongo_data
list_of_results.each do |result|
add_result_to_es(result)
end