定义架构

有两种替代使用架构推断的方法

使用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}""")
}