定义架构
除了使用架构推断之外,还有两种替代方案
使用 string
策略
当您将 schema.strategy
选项设置为 string
时,每个 DataFrame 列都将被分配 String
类型。
string
策略示例val df = spark.read
.format("org.neo4j.spark.DataSource")
.option("schema.strategy", "string")
.option("query", "MATCH (n:Person) WITH n LIMIT 2 RETURN id(n) as id, n.age as age")
.load()
此策略在属性类型可能不同时非常有用,例如当属性同时接受数字和字符串值时。
定义自定义架构
如果您需要更多控制,可以使用 .schema()
方法提供自己的架构。
自定义架构示例
import org.apache.spark.sql.types.{DataTypes, StructType, StructField}
val userSchema = StructType(
Array(
StructField("id", DataTypes.StringType),
StructField("age", DataTypes.StringType)
)
)
spark.read.format("org.neo4j.spark.DataSource")
.schema(userSchema)
.option("query", "MATCH (n:Person) WITH n LIMIT 2 RETURN id(n) as id, n.age as age")
.load()
用户定义的架构仅在属性的所有值都可以转换为所需类型时才有效。
如果您只需要转换部分值,请使用string
策略和一些自定义 Scala 或 Python 代码。
类型转换示例
import scala.jdk.CollectionConverters._
val result = df.collectAsList()
for (row <- result.asScala) {
// if <some specific condition> then convert like below
println(s"""Age is: ${row.getString(0).toLong}""")
}