You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Synapse的spark.read读取MongoDB _id返回乱码值?

Cosmos DB for MongoDB 连接Synapse Analytics时ObjectId乱码问题

使用CosmosDB MongoDB链接服务,将Azure Cosmos DB for MongoDB连接到Synapse Analytics工作区。已确认Cosmos/MongoDB中的objectID值有效(已在业务应用中正常使用)。

Cosmos DB数据资源管理器中的文档示例:

{
    "_id" : ObjectId("623a3902764504df1bc51620"),
    "name": "Dummy data"
}

环境配置

  • Cosmos DB集合已开启Analytical Storage Time to Live选项,集合可在Analytics Studio的Linked区域中显示。

测试1:PySpark环境验证

执行Spark SQL语句验证环境正常:

spark.sql("select unhex('623a3902764504df1bc51620') as bytes").show(truncate=False)

返回结果正常:

+-------------------------------------+
|bytes                                |
+-------------------------------------+
|[62 3A 39 02 76 45 04 DF 1B C5 16 20]|
+-------------------------------------+

测试2:读取Cosmos OLAP数据时ObjectId乱码

执行PySpark读取Cosmos OLAP数据:

df = spark.read\
    .format("cosmos.olap")\
    .option("spark.synapse.linkedService", "CosmosDbMongoDb1")\
    .option("spark.cosmos.container", "TABLENAME")\
    .load()

display(df.limit(10))

_id列返回乱码值:

"{"objectId":"b:9\u0002vE\u0004�\u001b�\u0016 "}"
objectId: ""b:9\u0002vE\u0004�\u001b�\u0016 ""

查看DataFrame Schema:

df.printSchema()

返回结果:

root
 |-- _rid: string (nullable = true)
 |-- _ts: long (nullable = true)
 |-- id: string (nullable = true)
 |-- _etag: string (nullable = true)
 |-- _id: struct (nullable = true)
 |    |-- objectId: string (nullable = true)
 |-- name: struct (nullable = true)
 |    |-- string: string (nullable = true)
..... snip ...

测试3:尝试转换ObjectId失败

执行转换语句:

df3 = df.select(unhex("_id.objectId"))

返回全null:

+-------------------+
|unhex(_id.objectId)|
+-------------------+
|               null|
|               null|
+-------------------+

执行df.select(unhex('_id.objectId'))仅返回Schema信息:

DataFrame[unhex(_id.objectId): binary]

测试4:SQL池查询同样乱码

在内置SQL池中执行查询:

SELECT TOP (100) JSON_VALUE([_id], '$.objectId') AS _id
 FROM [DB].[dbo].[TABLENAME]

返回乱码值:b:9vE��


测试5:创建外部表查询仍乱码

执行SQL创建外部表并查询:

%%sql
    create table TABLENAME using cosmos.olap options (
        spark.synapse.linkedService 'CosmosDbMongoDb1',
        spark.cosmos.container 'TABLENAME'
)

SELECT name, _id
FROM TABLENAME;

_id列返回带乱码的嵌套结构:

"{"schema":[{"name":"objectId","dataType":{},"nulla..."
schema: "[{\"name\":\"objectId\",\"dataType\":{},\"nullable\":true,..."
0: "{\"name\":\"objectId\",\"dataType\":{},\"nullable\":true,..."
name: "\"objectId\""
dataType: "{}"
nullable: "true"
metadata: "{"map":{}}"
map: "{}"
values: "[\"b:9\u0002vE\u0004�\u001b�\u0016 \"]"
0: "\"b:9\u0002vE\u0004�\u001

内容的提问来源于stack exchange,提问作者Monsieur le Crucudil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:13:11