Apache Spark Scala CosmosDB连接器将DataFrame写回数据库

时间:2017-08-03 03:22:22

标签: scala apache-spark azure-cosmosdb

我正在使用Scala中的Azure CosmosDB连接器使用Apache Spark,并且想知道是否有人有关于如何将我的DataFrame写回我的CosmosDB中的集合的示例或见解。目前,我能够连接到我的一个集合并返回数据并对其进行操作,但我想将结果写回同一数据库中的不同集合。

我创建了一个writeConfig,其中包含我想要写入的EndPoint,MasterKey,数据库和Collection。

然后我尝试使用以下行将其写入集合。

manipulatedData.toJSON.write.mode(SaveMode.Overwrite).cosmosDB(writeConfig)

这样运行正常,不会显示任何错误,但我的收藏中没有显示任何错误。

我查看了我在https://github.com/Azure/azure-cosmosdb-spark找到的文档,但没有找到将数据写回数据库的任何示例。

如果有一种比我正在做的更容易写入documentDB / cosmosDB的方法吗?我愿意接受任何选择。

感谢您的帮助。

1 个答案:

答案 0 :(得分:4)

您可以直接从Spark DataFrame保存到Cosmos DB,就像您所说的那样。您可能不需要使用toJSON,例如:

// Import SaveMode so you can Overwrite, Append, ErrorIfExists, Ignore
import org.apache.spark.sql.{Row, SaveMode, SparkSession}

// Create new DataFrame `df` which has slightly flights information 
// i.e. change the delay value to -999
val df = spark.sql("select -999 as delay, distance, origin, date, destination from c limit 5")

// Save to Cosmos DB (using Append in this case)
//    Ensure the baseConfig contains a Read-Write Key
//    The key provided in our examples is a Read-Only Key
df.write.mode(SaveMode.Append).cosmosDB(baseConfig)

至于文档,你是正确的,因为应该更好地调出save函数。我已创建Include in User Guide / sample scripts how to save to Cosmos DB #91来解决此问题。

至于保存但没有看到任何错误,您的配置是否使用只读密钥而不是读写密钥?我刚刚创建了Saving to CosmosDB using read-only key has no error #92,提出了同样的问题。