Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.spark.sql.catalyst.json

import java.text.ParsePosition
import java.util.Comparator

import scala.util.control.Exception.allCatch
Expand All @@ -28,7 +29,7 @@ import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.analysis.TypeCoercion
import org.apache.spark.sql.catalyst.expressions.ExprUtils
import org.apache.spark.sql.catalyst.json.JacksonUtils.nextUntil
import org.apache.spark.sql.catalyst.util.{DropMalformedMode, FailFastMode, ParseMode, PermissiveMode}
import org.apache.spark.sql.catalyst.util._
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils
Expand All @@ -37,6 +38,14 @@ private[sql] class JsonInferSchema(options: JSONOptions) extends Serializable {

private val decimalParser = ExprUtils.getDecimalParser(options.locale)

@transient
private lazy val timestampFormatter = TimestampFormatter(
options.timestampFormat,
options.timeZone,
options.locale)
@transient
private lazy val dateFormatter = DateFormatter(options.dateFormat, options.locale)

/**
* Infer the type of a collection of json records in three stages:
* 1. Infer the type of each record
Expand Down Expand Up @@ -121,7 +130,15 @@ private[sql] class JsonInferSchema(options: JSONOptions) extends Serializable {
DecimalType(bigDecimal.precision, bigDecimal.scale)
}
decimalTry.getOrElse(StringType)
case VALUE_STRING => StringType
case VALUE_STRING =>
val stringValue = parser.getText
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shall we abstract out this logic for all the text sources?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we can do that. There is some common code that could be shared. Can we do it in a separate PR?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure. How many text data sources already support it?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DateType is not inferred at all but there is another type inference code that could be shared between JSON and CSV (maybe somewhere else).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked PartitioningUtils.inferPartitionColumnValue, we try timestamp first and then date. Shall we follow it?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you mean partition value type inference will have a different result than json value type inference?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't mean type inference in partition values but you are probably right we should follow the same logic in schema inferring in datasources and partition value types.

Just wondering how it works for now, this code:

val unescapedRaw = unescapePathName(raw)
// try and parse the date, if no exception occurs this is a candidate to be resolved as
// TimestampType
DateTimeUtils.getThreadLocalTimestampFormat(timeZone).parse(unescapedRaw)
// SPARK-23436: see comment for date
val timestampValue = Cast(Literal(unescapedRaw), TimestampType, Some(timeZone.getID)).eval()
// Disallow TimestampType if the cast returned null
require(timestampValue != null)
Literal.create(timestampValue, TimestampType)
and this
if ((allCatch opt timeParser.parse(field)).isDefined) {
can use different timestamp patterns, or it is supposed to work only with default settings?

Maybe inferPartitionColumnValue should ask a datasource for inferring date/timestamp types?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the partition feature is shared between all the file-based sources, I think it's an overkill to make it differ with different data sources.

The simplest solution to me is asking all text sources to follow the behavior of partition value type inference.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, one time I tried to match it with CSV a long long ago but I kind of gave up due to behaviour changes IIRC. If that's possible, it should be awesome.

If that's difficult, matching the behaviour within text based datasource (meaning CSV and JSON I guess) should be good enough.

Copy link
Member

@HyukjinKwon HyukjinKwon Dec 10, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we switch the order here, we don't need the length check here, right?

@cloud-fan, that works only if we use default date/timestamp patterns. Both should do the exact match with pattern, which unfortunately the current parsing library (SimpleDateFormat) does not allow.

The order here is just to make it look better and both shouldn't be dependent on its order. I think we should support those inferences after completely switching the library to java.time.format.* (which does an exact match, and exists in JDK 8) without a legacy. That should make this change easier without a hole.

if ((allCatch opt timestampFormatter.parse(stringValue)).isDefined) {
TimestampType
} else if ((allCatch opt dateFormatter.parse(stringValue)).isDefined) {
DateType
} else {
StringType
}

case START_OBJECT =>
val builder = Array.newBuilder[StructField]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.sql.catalyst.json

import com.fasterxml.jackson.core.JsonFactory

import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.types._

class JsonInferSchemaSuite extends SparkFunSuite {

def checkType(options: Map[String, String], json: String, `type`: DataType): Unit = {
val jsonOptions = new JSONOptions(options, "GMT", "")
val inferSchema = new JsonInferSchema(jsonOptions)
val factory = new JsonFactory()
jsonOptions.setJacksonOptions(factory)
val parser = CreateJacksonParser.string(factory, json)
parser.nextToken()
val expectedType = StructType(Seq(StructField("a", `type`, true)))

assert(inferSchema.inferField(parser) === expectedType)
}

def checkTimestampType(pattern: String, json: String): Unit = {
checkType(Map("timestampFormat" -> pattern), json, TimestampType)
}

test("inferring timestamp type") {
checkTimestampType("yyyy", """{"a": "2018"}""")
checkTimestampType("yyyy=MM", """{"a": "2018=12"}""")
checkTimestampType("yyyy MM dd", """{"a": "2018 12 02"}""")
checkTimestampType(
"yyyy-MM-dd'T'HH:mm:ss.SSS",
"""{"a": "2018-12-02T21:04:00.123"}""")
checkTimestampType(
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX",
"""{"a": "2018-12-02T21:04:00.123567+01:00"}""")
}

def checkDateType(pattern: String, json: String): Unit = {
checkType(Map("dateFormat" -> pattern), json, DateType)
}

test("inferring date type") {
checkDateType("yyyy", """{"a": "2018"}""")
checkDateType("yyyy-MM", """{"a": "2018-12"}""")
checkDateType("yyyy-MM-dd", """{"a": "2018-12-02"}""")
}

test("strict inferring of date and timestamps") {
checkType(
options = Map(
"dateFormat" -> "yyyy-MM-dd",
"timestampFormat" -> "yyyy-MM-dd'T'HH:mm:ss.SSS"
),
json = """{"a": "2018-12-02T21:04:00.123"}""",
`type` = TimestampType
)
checkType(
options = Map(
"dateFormat" -> "yyyy-MM-dd",
"timestampFormat" -> "yyyy-MM-dd'T'HH:mm:ss.SSS"
),
json = """{"a": "2018-12-02"}""",
`type` = DateType
)
}
}