【问题标题】:How to import json file to mongodb using pyspark (or python)?如何使用pyspark(或python)将json文件导入mongodb?
【发布时间】:2019-09-08 23:26:12
【问题描述】:

在将pyspark与mongodb连接后,我尝试使用pyspark将文件中的json导入mongodb,

我使用的是 Ubuntu,我的文件在 (file:///home/user/Downloads/newd/hale.json) 我这样写 ('home/user/Downloads/newd/hale.json')

import json 
from pymongo import MongoClient
client =  MongoClient('localhost', 27017)
with open('home/user/Downloads/newdb/hale.json') as f:
file = json.load(f)

【问题讨论】:

  • 我想试试这个代码,但在 JSON (df = spark.read.csv(path = '/home/ahmad/Downloads/newdb/hale.csv', header=True, inferSchema=True )

标签: python json mongodb import pymongo


【解决方案1】:

这应该可以:

import json
from pymongo import MongoClient
client =  MongoClient('localhost', 27017)
with open('home/user/Downloads/newdb/hale.json') as f:
    file = json.load(f)

db = client['mydatabase']
db.mycollection.insert_one(file)

【讨论】:

  • 谢谢。我尝试了你的代码,但同样的错误(IndentationError: expected an indented block)
  • 在 python 中,标识是语法的重要组成部分。我怀疑你没有在上面的代码中识别出“file = json.load(f)”这一行。
  • 谢谢,我找到了这段代码:>>> df = spark.read.format('json').load('python/test_support/sql/people.json')
【解决方案2】:

您可以使用集合的方法 insert_one 或 insert_many,这取决于加载您的 json 文件是在加载 python 字典(JSON 对象)的列表(原始数组)还是 python dict(原始 JSON 对象)之后。 #in case of array of dictionaries client['your_database']['your_collection'].insert_many(file) #in case of dictionary client['your_database']['your_collection'].insert_one(file)

【讨论】:

  • ` with open('dump') as f: txt = f.read();文件 = json.loads(txt) `
猜你喜欢
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-25
  • 2018-12-25
  • 2015-10-13
  • 1970-01-01
  • 2019-07-10
  • 2014-12-24
相关资源
最近更新 更多