从pyspark插入多行到cosmosdb

时间:2018-09-03 10:26:07

标签: pyspark azure-cosmosdb

我试图在pyspark的数据框中插入多行。这是我的代码:

首先,我导入软件包:

import pydocumentdb
from pydocumentdb import document_client
from pydocumentdb import documents

然后,我定义connectionPolicy:

connectionPolicy = documents.ConnectionPolicy()
connectionPolicy.EnableEndpointDiscovery
connectionPolicy.PreferredLocations = {"Western Europe"}

凭据:

masterKey = 'yourmasterkey'
host = 'https://testcosmosdbasdada.documents.azure.com:443/'
client = document_client.DocumentClient(host,{'masterKey': masterKey}, connectionPolicy)

然后我定义一个数据库的名称和一个集合:

databaseId = 'pruebadb'
collectionId = 'collection1'

dbLink = 'dbs/' + databaseId
collLink = dbLink + '/colls/' + collectionId

注意:我应该在Azure套件中使用此名称创建数据库和集合。 然后,我可以使用或CreateDocument或UpsertDocument。我将使用UpsertDocument。

client.UpsertDocument(collLink,{'attribute1': 4}, options=None)

这有效!正如您在文档中看到的: website

但是我不知道如何一次插入一些行。这些证明不起作用:

1)

client.UpsertDocument(collLink,[{'attribute1': 4},{'attribute1': 2}], options=None)

“列表”对象没有属性“获取”

2)

client.UpsertDocument(collLink,[{'attribute1': 4},{'attribute1': 2}], options=None)

“列表”对象没有属性“获取”

3)

df = spark.read.csv('/FileStore/tables/points.csv', sep=';', header=True)
client.UpsertDocument(collLink, df, options=None)

“列表”对象没有属性“获取”

这些证明不起作用,因为我需要将dict作为UpsertDocument()的第二个参数。

是否有pydocumentdb或其他python库的任何功能?

使用pyspark将数据从数据帧插入CosmosDB的最佳性能方法是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用Spark MongoDB连接器提供的DataFrameWriter API来实现此目的,而不必依赖CosmosDB API。

下面的代码应该可以工作:

df.write.format("com.mongodb.spark.sql.DefaultSource")\
        .option("uri", "<CosmosDB URI>")\
        .option("database","CosmosDB Database Name")\
        .option("collection","CosmosDB Collection Name")\
        .mode("append").save()

您需要通过在spark-submit命令中使用--jars自变量或--packages自变量将Spark-MongoDB连接器添加到类路径。

例如:spark-submit --packages org.mongodb.spark:mongo-spark-connector_2.11:2.0.0 <YOUR_SRC_FILE>.py

有关DataFrameWriter API的更多信息,请访问:http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.DataFrameWriter

答案 1 :(得分:0)

感谢Sivaprasanna Sethuraman,我一直在调查。不必使用MongoDB。最终我发现:https://github.com/Azure/azure-cosmosdb-spark

如果需要在非空数据帧上插入,请小心使用模式附加:

writeConfig = {
 "Endpoint" : "yourhostcosmosdb",
 "Masterkey" : "yourmasterkey",
 "Database" : "pruebadb",
 "Collection" : "collection1",
}
df.write.format("com.microsoft.azure.cosmosdb.spark").mode('append').options(**writeConfig).save()