- spark Scala Mongodb- MongoTypeConversionException不能将STRING



如有任何帮助,我将不胜感激。

我正在尝试使用mongodb的数据建立一个数据框架。

val spark = SparkSession.builder()
.master("local")
.appName("app")
.config("spark.mongodb.input.uri", uri)
.config("spark.mongodb.input.collection", "collectionName")
.config("spark.mongodb.input.readPreference.name", "secondary")
.getOrCreate()
val df = MongoSpark.load(spark).limit(1)

和从那里我试图读取元素一行一行,数据框架的模式看起来像这样:

root
|-- A: struct (nullable = true)
|    |-- oid: string (nullable = true)
|-- B: boolean (nullable = true)
|-- C: string (nullable = true)
|-- D: string (nullable = true)
|-- E: array (nullable = true)
|    |-- element: struct (containsNull = true)
|    |    |-- a: string (nullable = true)
|    |    |-- b: string (nullable = true)
|    |    |-- c: string (nullable = true)
|    |    |-- d: string (nullable = true)

如果dataframe不包含E, dataframe.show()将正常输出。

但是,如果dataframe确实包含E,那么dataframe.show()将返回

Cannot cast STRING into a StructType(StructField(a,StringType,true), StructField(b,StringType,true), StructField(c,StringType,true), StructField(d,StringType,true)) (value: BsonString{value='http://...some url...'})

我尝试了几乎所有与这个问题相关的解决方案,但我仍然没有运气通过这个错误。

我该如何处理这个问题?谢谢你!

mongodb类型连接器的数据读取和数据转换问题。

我也面临同样的情况,但你可以通过以下方法避免它:

  1. Infer schema =True
  2. 将模式保存到另一个对象
  3. 再次读取"已保存模式",推断模式= False
  4. 加载数据,你可以用更新的数据做任何分析。

E实际上是一个包含多个字符串的对象数组。

mongodb文档示例

最新更新