Skip to content

[SPARK-2179][SQL] Public API for DataTypes and Schema - #1346

Closed
yhuai wants to merge 47 commits into
apache:masterfrom
yhuai:dataTypeAndSchema
Closed

yhuai wants to merge 47 commits into
apache:masterfrom
yhuai:dataTypeAndSchema

Conversation

@yhuai

@yhuai yhuai commented Jul 9, 2014

Copy link
Copy Markdown
Contributor

The current PR contains the following changes:

  • Expose DataTypes in the sql package (internal details are private to sql).
  • Users can create Rows.
  • Introduce applySchema to create a SchemaRDD by applying a schema: StructType to an RDD[Row].
  • Add a function simpleString to every DataType. Also, the schema represented by a StructType can be visualized by printSchema.
  • ScalaReflection.typeOfObject provides a way to infer the Catalyst data type based on an object. Also, we can compose typeOfObject with some custom logics to form a new function to infer the data type (for different use cases).
  • JsonRDD has been refactored to use changes introduced by this PR.
  • Add a field containsNull to ArrayType. So, we can explicitly mark if an ArrayType can contain null values. The default value of containsNull is false.

New APIs are introduced in the sql package object and SQLContext. You can find the scaladoc at
sql package object and SQLContext.

An example of using applySchema is shown below.

import org.apache.spark.sql._
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

val schema =
  StructType(
    StructField("name", StringType, false) ::
    StructField("age", IntegerType, true) :: Nil)

val people = sc.textFile("examples/src/main/resources/people.txt").map(_.split(",")).map(p => Row(p(0), p(1).trim.toInt))
val peopleSchemaRDD = sqlContext. applySchema(people, schema)
peopleSchemaRDD.printSchema
// root
// |-- name: string (nullable = false)
// |-- age: integer (nullable = true)

peopleSchemaRDD.registerAsTable("people")
sqlContext.sql("select name from people").collect.foreach(println)

I will add new contents to the SQL programming guide later.

JIRA: https://issues.apache.org/jira/browse/SPARK-2179

* Expose `DataType`s in the sql package (internal details are private to sql).
* Introduce `createSchemaRDD` to create a `SchemaRDD` from an `RDD` with a provided schema (represented by a `StructType`) and a provided function to construct `Row`,
* Add a function `simpleString` to every `DataType`. Also, the schema represented by a `StructType` can be visualized by `printSchema`.
@AmplabJenkins

Copy link
Copy Markdown

Merged build triggered.

@AmplabJenkins

Copy link
Copy Markdown

Merged build started.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Naming nit: functional lang usually uses "make", moreover SparkContext already has a public makeRDD.

@AmplabJenkins

Copy link
Copy Markdown

Merged build finished. All automated tests passed.

@AmplabJenkins

Copy link
Copy Markdown

All automated tests passed.
Refer to this link for build results: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16474/

@ueshin

ueshin commented Jul 10, 2014

Copy link
Copy Markdown
Member

Hi, I'm wondering if MapType will have something like containsNull for ArrayType.

@yhuai

yhuai commented Jul 10, 2014

Copy link
Copy Markdown
Contributor Author

Hi @ueshin, @marmbrus and I discussed about it. We think it is not semantically clear what a null means when it appears in the key or value field (considering a null is used to indicate a missing data value). So, we decided that key and value in a MapType should not contain any null value and we will not introduce containsNull to MapType. Does it make sense?

@ueshin

ueshin commented Jul 10, 2014

Copy link
Copy Markdown
Member

@yhuai, I understand. Thank you for your reply.

@rxin

rxin commented Jul 10, 2014

Copy link
Copy Markdown
Contributor

@yhuai I haven't looked at the changes yet, but can you make sure the end API is usable in Java?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

while you at it, add a blank line to separate each class

@yhuai

yhuai commented Jul 10, 2014

Copy link
Copy Markdown
Contributor Author

Yeah, I will make sure new APIs are usable in Java and Python.

@SparkQA

SparkQA commented Jul 10, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16528/consoleFull

@AmplabJenkins

Copy link
Copy Markdown

Refer to this link for build results: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16527/

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds the following public classes (experimental):
case class ArrayType(elementType: DataType) extends DataType {
case class StructField(name: String, dataType: DataType, nullable: Boolean) {
case class MapType(keyType: DataType, valueType: DataType) extends DataType {

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16528/consoleFull

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16547/consoleFull

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds the following public classes (experimental):
case class ArrayType(elementType: DataType) extends DataType {
case class StructField(name: String, dataType: DataType, nullable: Boolean) {
case class MapType(keyType: DataType, valueType: DataType) extends DataType {

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16547/consoleFull

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16553/consoleFull

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds the following public classes (experimental):
case class ArrayType(elementType: DataType) extends DataType {
case class StructField(name: String, dataType: DataType, nullable: Boolean) {
case class MapType(keyType: DataType, valueType: DataType) extends DataType {

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16553/consoleFull

@SparkQA

SparkQA commented Jul 11, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/16572/consoleFull

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17372/consoleFull

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch FAILED unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17372/consoleFull

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch DID NOT merge cleanly!
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17374/consoleFull

@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch FAILED unit tests.

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17374/consoleFull

Conflicts:
	sql/core/src/main/scala/org/apache/spark/sql/SQLContext.scala
	sql/core/src/main/scala/org/apache/spark/sql/SchemaRDD.scala
yhuai added 3 commits July 29, 2014 22:18
Conflicts:
	sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/BoundAttribute.scala
	sql/core/src/main/scala/org/apache/spark/sql/SQLContext.scala
	sql/core/src/main/scala/org/apache/spark/sql/api/java/JavaSQLContext.scala
	sql/core/src/main/scala/org/apache/spark/sql/json/JsonRDD.scala
@yhuai

yhuai commented Jul 30, 2014

Copy link
Copy Markdown
Contributor Author

@chenghao-intel containsNull and valueContainsNull can be used for further optimization. For example, let's say we have an ArrayType column and the element type is IntegerType. If elements of those arrays do not have null values, we can use a primitive array internal. Since we will expose data types to users, we need to introduce these two booleans with this PR. It can be hard to add them once users start to use these APIs.

@SparkQA

SparkQA commented Jul 30, 2014

Copy link
Copy Markdown

QA tests have started for PR 1346. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17423/consoleFull

@SparkQA

SparkQA commented Jul 30, 2014

Copy link
Copy Markdown

QA results for PR 1346:
- This patch PASSES unit tests.
- This patch merges cleanly
- This patch adds no public classes

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17423/consoleFull

@marmbrus

Copy link
Copy Markdown
Contributor

Thanks for working on this! Merged to master.

@asfgit asfgit closed this in 7003c16 Jul 30, 2014
@chenghao-intel

Copy link
Copy Markdown
Contributor

Thank you @yhuai for the explanation.

@yhuai

yhuai commented Jul 30, 2014

Copy link
Copy Markdown
Contributor Author

@yhuai yhuai mentioned this pull request Jul 30, 2014
@yhuai
yhuai deleted the dataTypeAndSchema branch July 31, 2014 21:11

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hi @yhuai , why we need to define schema as a StructType, but not directly as a Seq[StructField]? i tried to build a Seq[StructField] from JDBC metadata in #1612 https://github.com/apache/spark/pull/1612/files#diff-3 (it followed the code of your JsonRDD :)

it seems we do not need this StructType anywhere.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

For the completeness of our data types, we need StructType (Seq[StructField] is not a data type). For example, if the type of a filed is a struct, we need to have a way to describe that the type of this field is a struct. Also, because a row is basically a struct value, it is natural to use StructType to represent a schema.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

o, yep, StructType is needed, i mean
def applySchema(rowRDD: RDD[Row], schema: StructType): SchemaRDD
could be
def applySchema(rowRDD: RDD[Row], schema: Seq[StructField]): SchemaRDD

then we do not need to always use schema.fields.map(f => AttributeReference...)

we can direct schema.map(f => AttributeReference...)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This might be crazy... but if StructType <: Seq[StructField] then we could pass in either StructType or Seq[StructField]. Should be possible to do this fairly easily

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

good, i merged the change and used this API applySchema(rowRDD, appliedSchema) in #1612

xiliu82 pushed a commit to xiliu82/spark that referenced this pull request Sep 4, 2014
The current PR contains the following changes:
* Expose `DataType`s in the sql package (internal details are private to sql).
* Users can create Rows.
* Introduce `applySchema` to create a `SchemaRDD` by applying a `schema: StructType` to an `RDD[Row]`.
* Add a function `simpleString` to every `DataType`. Also, the schema represented by a `StructType` can be visualized by `printSchema`.
* `ScalaReflection.typeOfObject` provides a way to infer the Catalyst data type based on an object. Also, we can compose `typeOfObject` with some custom logics to form a new function to infer the data type (for different use cases).
* `JsonRDD` has been refactored to use changes introduced by this PR.
* Add a field `containsNull` to `ArrayType`. So, we can explicitly mark if an `ArrayType` can contain null values. The default value of `containsNull` is `false`.

New APIs are introduced in the sql package object and SQLContext. You can find the scaladoc at
[sql package object](http://yhuai.github.io/site/api/scala/index.html#org.apache.spark.sql.package) and [SQLContext](http://yhuai.github.io/site/api/scala/index.html#org.apache.spark.sql.SQLContext).

An example of using `applySchema` is shown below.
```scala
import org.apache.spark.sql._
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

val schema =
  StructType(
    StructField("name", StringType, false) ::
    StructField("age", IntegerType, true) :: Nil)

val people = sc.textFile("examples/src/main/resources/people.txt").map(_.split(",")).map(p => Row(p(0), p(1).trim.toInt))
val peopleSchemaRDD = sqlContext. applySchema(people, schema)
peopleSchemaRDD.printSchema
// root
// |-- name: string (nullable = false)
// |-- age: integer (nullable = true)

peopleSchemaRDD.registerAsTable("people")
sqlContext.sql("select name from people").collect.foreach(println)
```

I will add new contents to the SQL programming guide later.

JIRA: https://issues.apache.org/jira/browse/SPARK-2179

Author: Yin Huai <huai@cse.ohio-state.edu>

Closes apache#1346 from yhuai/dataTypeAndSchema and squashes the following commits:

1d45977 [Yin Huai] Clean up.
a6e08b4 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
c712fbf [Yin Huai] Converts types of values based on defined schema.
4ceeb66 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
e5f8df5 [Yin Huai] Scaladoc.
122d1e7 [Yin Huai] Address comments.
03bfd95 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
2476ed0 [Yin Huai] Minor updates.
ab71f21 [Yin Huai] Format.
fc2bed1 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
bd40a33 [Yin Huai] Address comments.
991f860 [Yin Huai] Move "asJavaDataType" and "asScalaDataType" to DataTypeConversions.scala.
1cb35fe [Yin Huai] Add "valueContainsNull" to MapType.
3edb3ae [Yin Huai] Python doc.
692c0b9 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
1d93395 [Yin Huai] Python APIs.
246da96 [Yin Huai] Add java data type APIs to javadoc index.
1db9531 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
d48fc7b [Yin Huai] Minor updates.
33c4fec [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
b9f3071 [Yin Huai] Java API for applySchema.
1c9f33c [Yin Huai] Java APIs for DataTypes and Row.
624765c [Yin Huai] Tests for applySchema.
aa92e84 [Yin Huai] Update data type tests.
8da1a17 [Yin Huai] Add Row.fromSeq.
9c99bc0 [Yin Huai] Several minor updates.
1d9c13a [Yin Huai] Update applySchema API.
85e9b51 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
e495e4e [Yin Huai] More comments.
42d47a3 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
c3f4a02 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
2e58dbd [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
b8b7db4 [Yin Huai] 1. Move sql package object and package-info to sql-core. 2. Minor updates on APIs. 3. Update scala doc.
68525a2 [Yin Huai] Update JSON unit test.
3209108 [Yin Huai] Add unit tests.
dcaf22f [Yin Huai] Add a field containsNull to ArrayType to indicate if an array can contain null values or not. If an ArrayType is constructed by "ArrayType(elementType)" (the existing constructor), the value of containsNull is false.
9168b83 [Yin Huai] Update comments.
fc649d7 [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
eca7d04 [Yin Huai] Add two apply methods which will be used to extract StructField(s) from a StructType.
949d6bb [Yin Huai] When creating a SchemaRDD for a JSON dataset, users can apply an existing schema.
7a6a7e5 [Yin Huai] Fix bug introduced by the change made on SQLContext.inferSchema.
43a45e1 [Yin Huai] Remove sql.util.package introduced in a previous commit.
0266761 [Yin Huai] Format
03eec4c [Yin Huai] Merge remote-tracking branch 'upstream/master' into dataTypeAndSchema
90460ac [Yin Huai] Infer the Catalyst data type from an object and cast a data value to the expected type.
3fa0df5 [Yin Huai] Provide easier ways to construct a StructType.
16be3e5 [Yin Huai] This commit contains three changes: * Expose `DataType`s in the sql package (internal details are private to sql). * Introduce `createSchemaRDD` to create a `SchemaRDD` from an `RDD` with a provided schema (represented by a `StructType`) and a provided function to construct `Row`, * Add a function `simpleString` to every `DataType`. Also, the schema represented by a `StructType` can be visualized by `printSchema`.
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Nov 4, 2026
… new ones (apache#1346)

### What changes were proposed in this pull request?

Every place that decides whether two Varka answers are "the same" now holds to the one definition from apache#1343, `VarkaSameAnswer`, and a lint rule keeps new ones from appearing. This is the second part of that work.

**Contract tests for the comparators in sql/core.** `VarkaSameAnswerCoreContractSuite` runs the shared table of tricky answer pairs against the comparators that only sql/core can reach, each at the level it is meant to answer at:
- `VarkaKernelRunner.compareBodies`, the check that the dense and the masked kernel body agree, at the type level. It runs over one-row Arrow outputs built from Spark's field for each pair's type, with the evaluator's width and floating flag. Those two helpers (`outputWidth`, `floatingOutput`) moved out of `VarkaEvaluatorBase` into `VarkaKernelRunner`, and are public because the runner and both callers sit in different packages.
- `VarkaExpressionHarness.sameRow`, at exact, and at the row level when a row has two unlike NaN inputs.
- `checkAnswer`'s row comparison, at any-NaN.
- `VarkaSparkFuzz`'s row-to-string comparison, at any-NaN, with decimals handled apart because a collected row carries its type's scale.

Every pair except four decimals the type cannot hold reaches `compareBodies`. Two decimal pairs that must be rejected were added: `1.50` against `1.51`, and a `DECIMAL(38,4)` value that differs from another only in its high 8 bytes, so a 64-bit comparison would pass it wrongly. A one-row batch with no nulls is one the running check skips, so the nullable-batch case and the selection bitmap are tested separately, as a two-row case in `VarkaEvaluatorComponentsSuite`.

**The suite-local rules now call the shared definition.** `VarkaEmitterFloatingArithSuite` and `VarkaFloatingLaneSuite` each kept their own idea of "any NaN is fine". They now decide by `VarkaSparkOracle.openNaN` and `VarkaSameAnswer.sameRow` instead. A row with two unlike NaN inputs no longer excuses every form in the first suite, and a column NaN no longer excuses every one of the second's two-operand expressions (`x1 - x2`, `try_divide(x1, x2)`). Only a NaN that is open by where it came from agrees as any NaN. All tests still pass: no Varka answer changed.

**A lint rule, `nan-compare` in `dev/varka_lint.py`.** Outside `VarkaSameAnswer` and the contract suites, it flags a hand-written comparison of two answers: their bits compared (raw or canonical), `Double.compare(a, b) == 0`, or two NaN tests joined by `&&`, unless `openNaN` decides the pair. It reads an expression across its continuation lines. It catches five of the six comparators that were removed. It cannot see one suite's one-column NaN relaxation, a boxed `equals`, or a comparison hidden behind a helper with another name. Over the whole tree it finds six expressions, none on a line this change writes. One of them accepts any NaN, `nanByNess` in `VarkaEmitterFloatingArithSuite`. The next part moves it onto the shared definition's any-NaN level.

**Left for later.** The shared definition treats a two-operand math function over two column NaNs as fixed, but fdlibm returns `x + y` for NaN operands, which is an add, so its payload depends on the JIT tier. When the math functions land on these suites, those nodes should be marked as either-payload. The plan's section 11 records this.

### Why are the changes needed?

apache#1343 gave Varka one definition of the same answer, but the checks that decide it were still written five different ways. Each way drew the line for NaN payloads and decimals in its own place, and the disagreement between them is what let the option matrix fail on a correct answer. Holding every comparator to one table of tricky pairs, and flagging new hand-written ones, keeps them from drifting apart again.

### Does this PR introduce _any_ user-facing change?

No. It changes tests, test helpers and developer tooling only.

### How was this patch tested?

- `dev/varka_matrix.sh --defaults` (both kernel bodies checked) over the two contract suites, `VarkaEvaluatorComponentsSuite`, `VarkaFloatingLaneSuite` and `VarkaEmitterFloatingArithSuite`.
- The lint rule's self-test, `python3 dev/varka_lint.py --selftest`, passes with 36 cases, and it also found the same six expressions over the tree.
- An independent high review and a medium review of its fixes found no wrong answers. The lint rule's three gaps they found are recorded in the plan's section 11, and one of them was fixed (a constant check that skipped every `Double.` call).
- Error Prone, scalastyle, lint-java and the plan, quote and pre-commit checks pass. The change counts 998 lines.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants