Github user yhuai commented on a diff in the pull request:

    https://github.com/apache/spark/pull/999#discussion_r13566856
  
    --- Diff: sql/core/src/main/scala/org/apache/spark/sql/json/JsonTable.scala 
---
    @@ -0,0 +1,364 @@
    +/*
    + * 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.json
    +
    +import org.apache.spark.annotation.Experimental
    +import org.apache.spark.rdd.RDD
    +import org.apache.spark.sql.catalyst.expressions._
    +import org.apache.spark.sql.execution.{ExistingRdd, SparkLogicalPlan}
    +import org.apache.spark.sql.catalyst.plans.logical._
    +import org.apache.spark.sql.catalyst.types._
    +import org.apache.spark.sql.SchemaRDD
    +import org.apache.spark.sql.Logging
    +import org.apache.spark.sql.catalyst.expressions.{Alias, 
AttributeReference, GetField}
    +
    +import com.fasterxml.jackson.databind.ObjectMapper
    +
    +import scala.collection.JavaConversions._
    +import scala.math.BigDecimal
    +import org.apache.spark.sql.catalyst.expressions.GetField
    +import org.apache.spark.sql.catalyst.expressions.AttributeReference
    +import org.apache.spark.sql.execution.SparkLogicalPlan
    +import org.apache.spark.sql.catalyst.expressions.Alias
    +import org.apache.spark.sql.catalyst.expressions.GetField
    +import org.apache.spark.sql.catalyst.expressions.AttributeReference
    +import org.apache.spark.sql.execution.SparkLogicalPlan
    +import org.apache.spark.sql.catalyst.expressions.Alias
    +import org.apache.spark.sql.catalyst.types.StructField
    +import org.apache.spark.sql.catalyst.types.StructType
    +import org.apache.spark.sql.catalyst.types.ArrayType
    +import org.apache.spark.sql.catalyst.expressions.GetField
    +import org.apache.spark.sql.catalyst.expressions.AttributeReference
    +import org.apache.spark.sql.execution.SparkLogicalPlan
    +import org.apache.spark.sql.catalyst.expressions.Alias
    +
    +sealed trait SchemaResolutionMode
    +
    +case object EAGER_SCHEMA_RESOLUTION extends SchemaResolutionMode
    +case class EAGER_SCHEMA_RESOLUTION_WITH_SAMPLING(val fraction: Double) 
extends SchemaResolutionMode
    +case object LAZY_SCHEMA_RESOLUTION extends SchemaResolutionMode
    +
    +/**
    + * :: Experimental ::
    + * Converts a JSON file to a SparkSQL logical query plan.  This 
implementation is only designed to
    + * work on JSON files that have mostly uniform schema.  The conversion 
suffers from the following
    + * limitation:
    + *  - The data is optionally sampled to determine all of the possible 
fields. Any fields that do
    + *    not appear in this sample will not be included in the final output.
    + */
    +@Experimental
    +object JsonTable extends Serializable with Logging {
    +  def inferSchema(
    +      json: RDD[String], sampleSchema: Option[Double] = None): LogicalPlan 
= {
    +    val schemaData = sampleSchema.map(json.sample(false, _, 
1)).getOrElse(json)
    +    val allKeys = 
parseJson(schemaData).map(getAllKeysWithValueTypes).reduce(_ ++ _)
    +
    +    // Resolve type conflicts
    +    val resolved = allKeys.groupBy {
    +      case (key, dataType) => key
    +    }.map {
    +      // Now, keys and types are organized in the format of
    +      // key -> Set(type1, type2, ...).
    +      case (key, typeSet) => {
    +        val fieldName = key.substring(1, key.length - 1).split("`.`").toSeq
    +        val dataType = typeSet.map {
    +          case (_, dataType) => dataType
    +        }.reduce((type1: DataType, type2: DataType) => 
getCompatibleType(type1, type2))
    +
    +        // Finally, we replace all NullType to StringType. We do not need 
to take care
    +        // StructType because all fields with a StructType are represented 
by a placeholder
    +        // StructType(Nil).
    +        dataType match {
    +          case NullType => (fieldName, StringType)
    +          case ArrayType(NullType) => (fieldName, ArrayType(StringType))
    +          case other => (fieldName, other)
    +        }
    +      }
    +    }
    +
    +    def makeStruct(values: Seq[Seq[String]], prefix: Seq[String]): 
StructType = {
    +      val (topLevel, structLike) = values.partition(_.size == 1)
    +      val topLevelFields = topLevel.filter {
    +        name => resolved.get(prefix ++ name).get match {
    +          case ArrayType(StructType(Nil)) => false
    +          case ArrayType(_) => true
    +          case struct: StructType => false
    +          case _ => true
    +        }
    +      }.map {
    +        a => StructField(a.head, resolved.get(prefix ++ a).get, nullable = 
true)
    +      }.sortBy {
    +        case StructField(name, _, _) => name
    +      }
    +
    +      val structFields: Seq[StructField] = structLike.groupBy(_(0)).map {
    +        case (name, fields) => {
    +          val nestedFields = fields.map(_.tail)
    +          val structType = makeStruct(nestedFields, prefix :+ name)
    +          val dataType = resolved.get(prefix :+ name).get
    +          dataType match {
    +            case array: ArrayType => Some(StructField(name, 
ArrayType(structType), nullable = true))
    +            case struct: StructType => Some(StructField(name, structType, 
nullable = true))
    +            // dataType is StringType means that we have resolved type 
conflicts involving
    +            // primitive types and complex types. So, the type of name has 
been relaxed to
    +            // StringType. Also, this field should have already been put 
in topLevelFields.
    +            case StringType => None
    +          }
    +        }
    +      }.flatMap(field => field).toSeq.sortBy {
    +        case StructField(name, _, _) => name
    +      }
    +
    +      StructType(topLevelFields ++ structFields)
    +    }
    +
    +    val schema = makeStruct(resolved.keySet.toSeq, Nil)
    +
    +    SparkLogicalPlan(
    +      ExistingRdd(
    +        asAttributes(schema),
    +        parseJson(json).map(asRow(_, schema))))
    +  }
    +
    +  // numericPrecedence and booleanPrecedence are from WidenTypes.
    +  // A widening conversion of a value with IntegerType and LongType to 
FloatType,
    +  // or of a value with LongType to DoubleType, may result in loss of 
precision
    +  // (some of the least significant bits of the value).
    +  val numericPrecedence =
    +    Seq(NullType, ByteType, ShortType, IntegerType, LongType, FloatType, 
DoubleType, DecimalType)
    +  // Boolean is only wider than Void
    +  val booleanPrecedence = Seq(NullType, BooleanType)
    +  val allPromotions: Seq[Seq[DataType]] = numericPrecedence :: 
booleanPrecedence :: Nil
    +
    +  /**
    +   * Returns the most general data type for two given data types.
    +   */
    +  protected def getCompatibleType(t1: DataType, t2: DataType): DataType = {
    --- End diff --
    
    No, I think we will not extend this object. I was thinking to only expose 
`inferSchema` to users. Should we do that?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastruct...@apache.org or file a JIRA ticket
with INFRA.
---

Reply via email to