-
Notifications
You must be signed in to change notification settings - Fork 29.3k
[SPARK-16496][SQL] Add wholetext as option for reading text in SQL. #14151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
dd2ed3d
7e91020
66d5b45
021039b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -304,7 +304,7 @@ def parquet(self, *paths): | |
|
|
||
| @ignore_unicode_prefix | ||
| @since(1.6) | ||
| def text(self, paths): | ||
| def text(self, paths, wholetext=False): | ||
| """ | ||
| Loads text files and returns a :class:`DataFrame` whose schema starts with a | ||
| string column named "value", and followed by partitioned columns if there | ||
|
|
@@ -313,11 +313,16 @@ def text(self, paths): | |
| Each line in the text file is a new row in the resulting DataFrame. | ||
|
|
||
| :param paths: string, or list of strings, for input path(s). | ||
| :param wholetext: if true, read each file from input path(s) as a single row. | ||
|
|
||
| >>> df = spark.read.text('python/test_support/sql/text-test.txt') | ||
| >>> df.collect() | ||
| [Row(value=u'hello'), Row(value=u'this')] | ||
| >>> df = spark.read.text('python/test_support/sql/text-test.txt', wholetext=True) | ||
| >>> df.collect() | ||
| [Row(value=u'hello\nthis')] | ||
| """ | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can you add a doctest for |
||
| self._set_opts(wholetext=wholetext) | ||
| if isinstance(paths, basestring): | ||
| paths = [paths] | ||
| return self._df(self._jreader.text(self._spark._sc._jvm.PythonUtils.toSeq(paths))) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| /* | ||
| * 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.execution.datasources | ||
|
|
||
| import java.io.Closeable | ||
| import java.net.URI | ||
|
|
||
| import org.apache.hadoop.conf.Configuration | ||
| import org.apache.hadoop.fs.Path | ||
| import org.apache.hadoop.io.Text | ||
| import org.apache.hadoop.mapreduce._ | ||
| import org.apache.hadoop.mapreduce.lib.input.CombineFileSplit | ||
| import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl | ||
|
|
||
| import org.apache.spark.input.WholeTextFileRecordReader | ||
|
|
||
| /** | ||
| * An adaptor from a [[PartitionedFile]] to an [[Iterator]] of [[Text]], which is all of the lines | ||
| * in that file. | ||
| */ | ||
| class HadoopFileWholeTextReader(file: PartitionedFile, conf: Configuration) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd like to remind that a
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We may want to override
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thank you, for catching this. |
||
| extends Iterator[Text] with Closeable { | ||
| private val iterator = { | ||
| val fileSplit = new CombineFileSplit( | ||
| Array(new Path(new URI(file.filePath))), | ||
| Array(file.start), | ||
| Array(file.length), | ||
| // TODO: Implement Locality | ||
| Array.empty[String]) | ||
| val attemptId = new TaskAttemptID(new TaskID(new JobID(), TaskType.MAP, 0), 0) | ||
| val hadoopAttemptContext = new TaskAttemptContextImpl(conf, attemptId) | ||
| val reader = new WholeTextFileRecordReader(fileSplit, hadoopAttemptContext, 0) | ||
| reader.initialize(fileSplit, hadoopAttemptContext) | ||
| new RecordReaderIterator(reader) | ||
| } | ||
|
|
||
| override def hasNext: Boolean = iterator.hasNext | ||
|
|
||
| override def next(): Text = iterator.next() | ||
|
|
||
| override def close(): Unit = iterator.close() | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,12 +17,16 @@ | |
|
|
||
| package org.apache.spark.sql.execution.datasources.text | ||
|
|
||
| import java.io.Closeable | ||
|
|
||
| import org.apache.hadoop.conf.Configuration | ||
| import org.apache.hadoop.fs.{FileStatus, Path} | ||
| import org.apache.hadoop.io.Text | ||
| import org.apache.hadoop.mapreduce.{Job, TaskAttemptContext} | ||
|
|
||
| import org.apache.spark.TaskContext | ||
| import org.apache.spark.sql.{AnalysisException, Row, SparkSession} | ||
| import org.apache.spark.broadcast.Broadcast | ||
| import org.apache.spark.sql.{AnalysisException, SparkSession} | ||
| import org.apache.spark.sql.catalyst.InternalRow | ||
| import org.apache.spark.sql.catalyst.expressions.UnsafeRow | ||
| import org.apache.spark.sql.catalyst.expressions.codegen.{BufferHolder, UnsafeRowWriter} | ||
|
|
@@ -53,6 +57,14 @@ class TextFileFormat extends TextBasedFileFormat with DataSourceRegister { | |
| } | ||
| } | ||
|
|
||
| override def isSplitable( | ||
| sparkSession: SparkSession, | ||
| options: Map[String, String], | ||
| path: Path): Boolean = { | ||
| val textOptions = new TextOptions(options) | ||
| super.isSplitable(sparkSession, options, path) && !textOptions.wholeText | ||
| } | ||
|
|
||
| override def inferSchema( | ||
| sparkSession: SparkSession, | ||
| options: Map[String, String], | ||
|
|
@@ -97,14 +109,25 @@ class TextFileFormat extends TextBasedFileFormat with DataSourceRegister { | |
| assert( | ||
| requiredSchema.length <= 1, | ||
| "Text data source only produces a single data column named \"value\".") | ||
|
|
||
| val textOptions = new TextOptions(options) | ||
| val broadcastedHadoopConf = | ||
| sparkSession.sparkContext.broadcast(new SerializableConfiguration(hadoopConf)) | ||
|
|
||
| readToUnsafeMem(broadcastedHadoopConf, requiredSchema, textOptions.wholeText) | ||
| } | ||
|
|
||
| private def readToUnsafeMem(conf: Broadcast[SerializableConfiguration], | ||
| requiredSchema: StructType, wholeTextMode: Boolean): | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. private def readToUnsafeMem(
conf: Broadcast[SerializableConfiguration],
requiredSchema: StructType,
wholeTextMode: Boolean): (PartitionedFile) => Iterator[UnsafeRow] |
||
| (PartitionedFile) => Iterator[UnsafeRow] = { | ||
|
|
||
| (file: PartitionedFile) => { | ||
| val reader = new HadoopFileLinesReader(file, broadcastedHadoopConf.value.value) | ||
| val confValue = conf.value.value | ||
| val reader = if (!wholeTextMode) { | ||
| new HadoopFileLinesReader(file, confValue) | ||
| } else { | ||
| new HadoopFileWholeTextReader(file, confValue) | ||
| } | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can avoid using val reader = if (!wholeTextMode) {
new HadoopFileLinesReader(file, confValue)
} else {
new HadoopFileWholeTextReader(file, confValue)
} |
||
| Option(TaskContext.get()).foreach(_.addTaskCompletionListener(_ => reader.close())) | ||
|
|
||
| if (requiredSchema.isEmpty) { | ||
| val emptyUnsafeRow = new UnsafeRow(0) | ||
| reader.map(_ => emptyUnsafeRow) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -39,6 +39,54 @@ class TextSuite extends QueryTest with SharedSQLContext { | |
| verifyFrame(spark.read.text(testFile)) | ||
| } | ||
|
|
||
| test("reading text file with option wholetext=true") { | ||
| val df = spark.read.option("wholetext", "true") | ||
| .format("text").load(testFile) | ||
| // schema | ||
| assert(df.schema == new StructType().add("value", StringType)) | ||
|
|
||
| // verify content | ||
| val data = df.collect() | ||
| assert(data(0) == | ||
| Row( | ||
| // scalastyle:off nonascii | ||
| """This is a test file for the text data source | ||
| |1+1 | ||
| |数据砖头 | ||
| |"doh" | ||
| |""".stripMargin)) | ||
| // scalastyle:on nonascii | ||
| assert(data.length == 1) | ||
| } | ||
|
|
||
| test("reading multiple text files with option wholetext=true") { | ||
| import org.apache.spark.sql.catalyst.util._ | ||
| withTempDir { dir => | ||
| val file1 = new File(dir, "text1.txt") | ||
| stringToFile(file1, | ||
| """text file 1 contents. | ||
| |From: None to: ?? | ||
| """.stripMargin) | ||
| val file2 = new File(dir, "text2.txt") | ||
| stringToFile(file2, "text file 2 contents.") | ||
| val file3 = new File(dir, "text3.txt") | ||
| stringToFile(file3, "text file 3 contents.") | ||
| val df = spark.read.option("wholetext", "true").text(dir.getAbsolutePath) | ||
| // Since wholetext option reads each file into a single row, df.length should be no. of files. | ||
| val data = df.sort("value").collect() | ||
| assert(data.length == 3) | ||
| // Each files should represent a single Row/element in Dataframe/Dataset | ||
| assert(data(0) == Row( | ||
| """text file 1 contents. | ||
| |From: None to: ?? | ||
| """.stripMargin)) | ||
| assert(data(1) == Row( | ||
| """text file 2 contents.""".stripMargin)) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nit: should we also check for |
||
| assert(data(2) == Row( | ||
| """text file 3 contents.""".stripMargin)) | ||
| } | ||
| } | ||
|
|
||
| test("SPARK-12562 verify write.text() can handle column name beyond `value`") { | ||
| val df = spark.read.text(testFile).withColumnRenamed("value", "adwrasdf") | ||
|
|
||
|
|
@@ -185,10 +233,9 @@ class TextSuite extends QueryTest with SharedSQLContext { | |
| val data = df.collect() | ||
| assert(data(0) == Row("This is a test file for the text data source")) | ||
| assert(data(1) == Row("1+1")) | ||
| // non ascii characters are not allowed in the code, so we disable the scalastyle here. | ||
| // scalastyle:off | ||
| // scalastyle:off nonascii | ||
| assert(data(2) == Row("数据砖头")) | ||
| // scalastyle:on | ||
| // scalastyle:on nonascii | ||
| assert(data(3) == Row("\"doh\"")) | ||
| assert(data.length == 4) | ||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm, can't we just do
\\n?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That would fail the test, I suppose. I can give that a try though.