定义模式
使用模式推断有两种替代方案
使用 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}""")
}