3

Spark Version: spark-2.0.1-bin-hadoop2.7 Scala: 2.11.8스칼라 : 나는 DataFrame에 원시 CSV를로드하고 NULL

를 반환 스파크 SQL의 TO_DATE (UNIX_TIMESTAMP). csv에서 열은 날짜 형식으로 지원되지만 2016-1025 대신 20161025로 작성됩니다. 매개 변수 date_format에는 yyyy-mm-dd 형식으로 변환해야하는 열 이름 문자열이 포함되어 있습니다. 다음 코드에서

, 내가 먼저 schema을 통해 StringType 같은 날짜 칼럼의 CSV를로드 한 후 나는 date_format가 비어 있지 않은 경우 확인, 그 String에서 Date으로 변환해야 열 다음, 거기입니다 unix_timestampto_date을 사용하여 각 열을 전송하십시오. 그러나 csv_df.show()에서 반환되는 행은 모두 null입니다.

def read_csv(csv_source:String, delimiter:String, is_first_line_header:Boolean, 
    schema:StructType, date_format:List[String]): DataFrame = { 
    println("|||| Reading CSV Input ||||") 

    var csv_df = sqlContext.read 
     .format("com.databricks.spark.csv") 
     .schema(schema) 
     .option("header", is_first_line_header) 
     .option("delimiter", delimiter) 
     .load(csv_source) 
    println("|||| Successfully read CSV. Number of rows -> " + csv_df.count() + " ||||") 
    if(date_format.length > 0) { 
     for (i <- 0 until date_format.length) { 
      csv_df = csv_df.select(to_date(unix_timestamp(
       csv_df(date_format(i)), "yyyy-­MM-­dd").cast("timestamp"))) 
      csv_df.show() 
     } 
    } 
    csv_df 
} 

반환 상위 20 행 :

+-------------------------------------------------------------------------+ 
|to_date(CAST(unix_timestamp(prom_price_date, YYYY-­MM-­DD) AS TIMESTAMP))| 
+-------------------------------------------------------------------------+ 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
|                  null| 
+-------------------------------------------------------------------------+ 

이유는 모든 null는 무엇입니까?

답변

8

yyyy-MM-dd하는 yyyyMMdd을 변환하려면 다음을 수행 할 수 있습니다

date_format(unix_timestamp(col, "yyyyMMdd").cast("timestamp"), "yyyy-MM-dd") 
: 기능

spark.sql("""SELECT DATE_FORMAT(
    CAST(UNIX_TIMESTAMP('20161025', 'yyyyMMdd') AS TIMESTAMP), 'yyyy-MM-dd' 
)""")