【问题标题】:Azure Synapse - How to read data from Azure Cosmos DB container containing multiple types in same collection?Azure Synapse - 如何从同一集合中包含多种类型的 Azure Cosmos DB 容器读取数据?
【发布时间】:2021-12-13 11:49:30
【问题描述】:

我在 Azure Cosmos DB 中有一个容器,该容器在同一个容器中有多种文档类型。因此,根据类型,密钥对会发生变化。我正在尝试使用以下代码从 Synapse 中的此容器中读取数据:

cfg = {
"spark.cosmos.accountEndpoint": Endpoint,
"spark.cosmos.accountKey": accountKey,
"spark.cosmos.database": databaseName,
"spark.cosmos.container": containerName,
}

df = spark.read.format("cosmos.oltp").options(**cfg)\
    .option("spark.cosmos.read.inferSchema.enabled","true").load()

但是,我通过此数据框获取的架构属于第一行的类型。如何确保我读取一种特定类型的数据并相应地推断架构?

【问题讨论】:

    标签: azure-cosmosdb azure-synapse


    【解决方案1】:

    如果您不想使用上面的 customQuery 配置选项(这实际上会对发送到 Cosmos 后端的查询进行硬编码,而不是依赖 Spark 中的过滤器下推),您还可以使用配置选项“spark. cosmos.read.inferSchema.query”——这只会改变用于模式推断的查询——但在其他方面依赖于过滤器下推(在某些情况下可以提高查询性能)

    cfg = {
    "spark.cosmos.accountEndpoint": Endpoint,
    "spark.cosmos.accountKey": accountKey,
    "spark.cosmos.database": databaseName,
    "spark.cosmos.container": containerName,
    "spark.cosmos.read.inferSchema.query": "SELECT * FROM c WHERE c.typ = TYPE_NAME"
    }
    

    【讨论】:

      【解决方案2】:

      如果您在一个容器中有多种文档类型,请使用配置中的spark.cosmos.read.customQuery 参数来获取特定文档类型作为 spark 数据框:

      cfg = {
      "spark.cosmos.accountEndpoint": Endpoint,
      "spark.cosmos.accountKey": accountKey,
      "spark.cosmos.database": databaseName,
      "spark.cosmos.container": containerName,
      "spark.cosmos.read.customQuery": "SELECT * FROM c WHERE c.typ = TYPE_NAME"
      }
      
      df = spark.read.format("cosmos.oltp").options(**cfg)\
          .option("spark.cosmos.read.inferSchema.enabled","true").load()
      

      有关详细信息,请参阅 this 文档。

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 1970-01-01
        • 2020-06-23
        • 2021-06-13
        • 2018-06-02
        • 1970-01-01
        • 2017-07-21
        • 2019-02-17
        • 2018-10-12
        相关资源
        最近更新 更多