开发者社区> 问答> 正文

如何从代码外部提供spark / scala中的模式

我想读取ex:schema_file的文件,它将包含模式,并希望在代码中使用它来创建DataFrame

我已阅读过ConfigFactory提供架构但无法使用它,因为将来可能会更改架构。

schema[
{

 columnName = EXAMPLE_1
 type = string

},
{

 columnName = EXAMPLE_2
 type = string

},
{

 columnName = EXAMPLE_3
 type = string

}
]
如果我使用这个,我必须读取每个columnName

config.getString("schema.ColumnName1")

但列不固定,可以更改列数。

此外,我尝试使用案例类,但在那,我还需要指定每个字段。

如何从代码外部读取模式。

展开
收起
社区小助手 2018-12-21 10:55:21 1760 0
1 条回答
写回答
取消 提交回答
  • 社区小助手是spark中国社区的管理员,我会定期更新直播回顾等资料和文章干货,还整合了大家在钉群提出的有关spark的问题及回答。

    可以尝试使用此库来加载配置并将其映射到scala类:https://github.com/pureconfig/pureconfig

    import scala.io.Source
    import scala.util.parsing.combinator.syntactical.StandardTokenParsers

    object Application extends App {
    override def main(args: Array[String]): Unit = {

    val fileContents = Source.fromFile("src/main/resources/schema_file").getLines.mkString
    print(ConfigDSL.parseSchema(fileContents))

    }
    }

    case class Schema(columns: List[Column])
    case class Column(columnName: String, columnType: String)

    object ConfigDSL extends StandardTokenParsers {
    lexical.delimiters ++= List("[", "]", "{", "}", ",", " ", "=", "n")
    lexical.reserved ++= List("schema", "type", "columnName")

    def parseSchema(schemaString: String): Schema =

    schema(new lexical.Scanner(schemaString)) match {
      case Success(columns, _) => Schema(columns)
      case Failure(msg, _) => throw new RuntimeException(msg)
      case Error(msg, _) => throw new RuntimeException(msg)
    }
    

    def schema: Parser[List[Column]] =

    "schema" ~ "[" ~ listOfColumns ~ "]" ^^ { case _ ~ _ ~ recipeList ~ _ => recipeList }
    

    def columnDefinition: Parser[Column] =

    "{" ~ "columnName" ~ "=" ~ ident ~ "type" ~ "=" ~ ident ~ "}" ^^ {
      case _ ~ _ ~ _ ~ column ~ _ ~ _ ~ columnType ~ _ => Column(column, columnType)
    }
    

    def listOfColumns: Parser[List[Column]] =

    repsep(columnDefinition, ",")  ^^ { stepList: List[Column] => stepList}

    }

    2019-07-17 23:23:17
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Hybrid Cloud and Apache Spark 立即下载
Scalable Deep Learning on Spark 立即下载
Comparison of Spark SQL with Hive 立即下载