You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@iotdb.apache.org by qi...@apache.org on 2019/05/09 05:13:06 UTC
[incubator-iotdb] branch master updated: [IOTDB-64]
TsFile-Spark-Connector update (#108)
This is an automated email from the ASF dual-hosted git repository.
qiaojialin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 3568b32 [IOTDB-64] TsFile-Spark-Connector update (#108)
3568b32 is described below
commit 3568b32215256e6acf7195649433d0144bedec81
Author: RUI, LEI <33...@users.noreply.github.com>
AuthorDate: Thu May 9 13:13:02 2019 +0800
[IOTDB-64] TsFile-Spark-Connector update (#108)
* add logical part for global time filters from partition problem
* Update README.md, doc, dependency version pom, .travis.yml
* modify scala version to 2.11.8 and restrict java version to 8, change scalatest version from 2.12 to 2.1
---
.travis.yml | 27 +-
.../Documentation/UserGuideV0.7.0/7-Tools-spark.md | 286 ++++----
pom.xml | 6 +-
spark/README.md | 407 +++++++----
spark/pom.xml | 7 +-
.../org/apache/iotdb/tsfile/io/CreateTSFile.java | 150 ----
.../java/org/apache/iotdb/tsfile/io/HDFSInput.java | 147 ++++
.../apache/iotdb/tsfile/io/HDFSInputStream.java | 111 ---
.../io/{HDFSOutputStream.java => HDFSOutput.java} | 52 +-
.../apache/iotdb/tsfile/io/TsFileOutputFormat.java | 10 +-
.../apache/iotdb/tsfile/io/TsFileRecordWriter.java | 19 +-
.../java/org/apache/iotdb/tsfile/qp/Executor.java | 51 --
.../org/apache/iotdb/tsfile/qp/QueryProcessor.java | 153 -----
.../iotdb/tsfile/qp/common/BasicOperator.java | 75 --
.../iotdb/tsfile/qp/common/FilterOperator.java | 157 -----
.../apache/iotdb/tsfile/qp/common/Operator.java | 47 --
.../apache/iotdb/tsfile/qp/common/SQLConstant.java | 150 ----
.../apache/iotdb/tsfile/qp/common/SingleQuery.java | 63 --
.../apache/iotdb/tsfile/qp/common/TSQueryPlan.java | 63 --
.../qp/exception/BasicOperatorException.java | 34 -
.../tsfile/qp/exception/DNFOptimizeException.java | 34 -
.../qp/exception/LogicalOptimizeException.java | 33 -
.../tsfile/qp/exception/MergeFilterException.java | 30 -
.../qp/exception/QueryOperatorException.java | 29 -
.../qp/exception/QueryProcessorException.java | 41 --
.../tsfile/qp/exception/RemoveNotException.java | 34 -
.../tsfile/qp/optimizer/DNFFilterOptimizer.java | 157 -----
.../tsfile/qp/optimizer/IFilterOptimizer.java | 34 -
.../qp/optimizer/MergeSingleFilterOptimizer.java | 141 ----
.../tsfile/qp/optimizer/PhysicalOptimizer.java | 228 ------
.../tsfile/qp/optimizer/RemoveNotOptimizer.java | 108 ---
.../scala/org/apache/iotdb/tsfile/Converter.scala | 762 ++++++++++++---------
.../org/apache/iotdb/tsfile/DefaultSource.scala | 178 ++---
.../apache/iotdb/tsfile/TsFileOutputWriter.scala | 52 +-
.../apache/iotdb/tsfile/TsFileWriterFactory.scala | 42 +-
.../scala/org/apache/iotdb/tsfile/package.scala | 36 +-
spark/src/test/resources/test.tsfile | Bin 1406 -> 0 bytes
.../cn/edu/tsinghua/tsfile/ConverterTest.scala | 130 ----
.../scala/cn/edu/tsinghua/tsfile/TSFileSuit.scala | 194 ------
.../scala/org/apache/iotdb/tool/TsFileExample.java | 106 +++
.../scala/org/apache/iotdb/tool/TsFileWrite.java | 215 ++++++
.../org/apache/iotdb/tsfile/ConverterTest.scala | 266 +++++++
.../org/apache/iotdb/tsfile/HDFSInputTest.java | 79 +++
.../scala/org/apache/iotdb/tsfile/TSFileSuit.scala | 217 ++++++
.../tsfile/common/constant/QueryConstant.java | 8 +
.../iotdb/tsfile/read/TsFileSequenceReader.java | 2 +-
.../apache/iotdb/tsfile/read/common/TimeRange.java | 289 ++++++++
.../tsfile/read/controller/MetadataQuerier.java | 40 ++
.../read/controller/MetadataQuerierByFileImpl.java | 132 +++-
.../query/executor/ExecutorWithTimeGenerator.java | 33 +-
.../tsfile/read/query/executor/TsFileExecutor.java | 64 +-
.../apache/iotdb/tsfile/write/TsFileWriter.java | 12 +
.../iotdb/tsfile/write/writer/TsFileIOWriter.java | 11 +
.../iotdb/tsfile/read/ReadInPartitionTest.java | 158 +++++
.../org/apache/iotdb/tsfile/read/ReadTest.java | 2 +-
.../iotdb/tsfile/read/common/TimeRangeTest.java | 225 ++++++
.../controller/MetadataQuerierByFileImplTest.java | 57 +-
57 files changed, 3072 insertions(+), 3122 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index ba2a8ba..6202bf5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -31,6 +31,11 @@ matrix:
- os: osx
osx_image: xcode10.1 # with JDK11.0.1+13 installed
name: osx-oraclejdk11
+ script:
+ - java -version
+ - mvn -version
+ - mvn -B apache-rat:check
+ - mvn -B clean package -pl iotdb,grafana,iotdb-cli,example,:kafka-example,:rocketmq-example -am integration-test
- os: osx
osx_image: xcode9.3 # with JDK1.8.0_112-b16 installed
name: osx-oraclejdk8
@@ -44,6 +49,11 @@ matrix:
- AdoptOpenJDK/openjdk
update: true
casks: adoptopenjdk-openjdk11
+ script:
+ - java -version
+ - mvn -version
+ - mvn -B apache-rat:check
+ - mvn -B clean package -pl iotdb,grafana,iotdb-cli,example,:kafka-example,:rocketmq-example -am integration-test
- os: osx
osx_image: xcode9.3 # with JDK1.8.0_112-b16 installed
name: osx-openjdk8
@@ -61,7 +71,7 @@ matrix:
- choco install jdk11 -params 'installdir=c:\\java11'
- export PATH=$PATH:"/c/java11/bin"
- export JAVA_HOME="/c/java11"
- - wget https://www-eu.apache.org/dist/maven/maven-3/3.6.1/binaries/apache-maven-3.6.1-bin.zip
+ - wget -q https://www-eu.apache.org/dist/maven/maven-3/3.6.1/binaries/apache-maven-3.6.1-bin.zip
- /C/Progra~1/7-Zip/7z.exe x apache-maven-3.6.1-bin.zip -o/c/mvn361
- export "MAVEN_HOME=/c/mvn361/apache-maven-3.6.1"
- export "M2_HOME=/c/mvn361/apache-maven-3.6.1"
@@ -69,13 +79,7 @@ matrix:
script:
- java -version
- mvn -version
- - mvn -B clean integration-test
- cache:
- directories:
- - '$HOME/.m2/repository'
- - '$HOME/.sonar/cache'
- - '/c/java11'
- - '/c/mvn361'
+ - mvn -B clean package -pl iotdb,grafana,iotdb-cli,example,:kafka-example,:rocketmq-example -am integration-test
- os: windows
language: c
@@ -108,7 +112,7 @@ matrix:
- export PATH=$JAVA_HOME/bin:$PATH
script:
- java -version
- - mvn -B clean integration-test
+ - mvn -B clean package -pl iotdb,grafana,iotdb-cli,example,:kafka-example,:rocketmq-example -am integration-test
- os: linux
name: linux-openjdk8
dist: trusty
@@ -121,6 +125,11 @@ matrix:
name: linux-oraclejdk11
dist: trusty
jdk: oraclejdk11
+ script:
+ - java -version
+ - mvn -version
+ - mvn -B apache-rat:check
+ - mvn -B clean package -pl iotdb,grafana,iotdb-cli,example,:kafka-example,:rocketmq-example -am integration-test
cache:
directories:
diff --git a/docs/Documentation/UserGuideV0.7.0/7-Tools-spark.md b/docs/Documentation/UserGuideV0.7.0/7-Tools-spark.md
index adf28c6..3f88d4e 100644
--- a/docs/Documentation/UserGuideV0.7.0/7-Tools-spark.md
+++ b/docs/Documentation/UserGuideV0.7.0/7-Tools-spark.md
@@ -19,105 +19,210 @@
-->
+
<!-- TOC -->
- [TsFile-Spark-Connector User Guide](#tsfile-spark-connector-user-guide)
- - [Dependencies & Version](#dependencies--version)
- - [Quick Start](#quick-start)
- - [Step1: Build TsFile-Spark-Connector](#step1-build-tsfile-spark-connector)
- - [Step2: Import Connector Lib into Spark](#step2-import-connector-lib-into-spark)
- - [Step3: Use Connector in Spark](#step3-use-connector-in-spark)
- - [5.2.1.1 Local Mode](#5211-local-mode)
- - [5.2.1.2 Distributed Mode](#5212-distributed-mode)
- - [Detail: Conversion between TsFile and Spark](#detail-conversion-between-tsfile-and-spark)
- - [TsFile Type <-> SparkSQL type](#tsfile-type---sparksql-type)
- - [TsFile Schema <-> SparkSQL Table Structure](#tsfile-schema---sparksql-table-structure)
- - [the default way](#the-default-way)
- - [unfolding delta_object column](#unfolding-delta_object-column)
- - [Example](#example)
- - [5.1 Scala API](#51-scala-api)
+ - [1. About TsFile-Spark-Connector](#1-about-tsfile-spark-connector)
+ - [2. System Requirements](#2-system-requirements)
+ - [3. Quick Start](#3-quick-start)
+ - [Local Mode](#local-mode)
+ - [Distributed Mode](#distributed-mode)
+ - [4. Data Type Correspondence](#4-data-type-correspondence)
+ - [5. Schema Inference](#5-schema-inference)
+ - [6. Scala API](#6-scala-api)
+ - [Example 1: read from the local file system](#example-1-read-from-the-local-file-system)
+ - [Example 2: read from the hadoop file system](#example-2-read-from-the-hadoop-file-system)
+ - [Example 3: read from a specific directory](#example-3-read-from-a-specific-directory)
+ - [Example 4: query](#example-4-query)
+ - [Example 5: write](#example-5-write)
+ - [Appendix A: Old Design of Schema Inference](#appendix-a-old-design-of-schema-inference)
+ - [the default way](#the-default-way)
+ - [unfolding delta_object column](#unfolding-delta_object-column)
+ - [Appendix B: Old Note](#appendix-b-old-note)
<!-- /TOC -->
+
+<a id="tsfile-spark-connector-user-guide"></a>
# TsFile-Spark-Connector User Guide
+<a id="1-about-tsfile-spark-connector"></a>
+## 1. About TsFile-Spark-Connector
+
TsFile-Spark-Connector implements the support of Spark for external data sources of Tsfile type. This enables users to read, write and query Tsfile by Spark.
-## Dependencies & Version
+With this connector, you can
+* load a single TsFile, from either the local file system or hdfs, into Spark
+* load all files in a specific directory, from either the local file system or hdfs, into Spark
+* write data from Spark into TsFile
-The versions required for Spark and Java are as follow:
+<a id="2-system-requirements"></a>
+## 2. System Requirements
-| Spark Version | Scala Version | Java Version | TsFile |
-| ------------- | ------------- | ------------ |------- |
-| `2.0+` | `2.11` | `1.8` | `0.7.0`|
+|Spark Version | Scala Version | Java Version | TsFile |
+|------------- | ------------- | ------------ |------------ |
+| `2.0.1` | `2.11.8` | `1.8` | `0.8.0-SNAPSHOT`|
> Note: For more information about how to download and use TsFile, please see the following link: https://github.com/apache/incubator-iotdb/tree/master/tsfile.
-## Quick Start
-
-### Step1: Build TsFile-Spark-Connector
-
-To build TsFile-Spark-Connector, you can use the following command:
-
-```
-mvn clean scala:compile compile package
-```
-
-In addition, you can also choose to download the available lib package directly from our website. The download link will be comming soon.
-
-### Step2: Import Connector Lib into Spark
-
-* import tsfile-spark-connector.jar into spark lib
-* replace libthrift-0.9.2.jar and libfb303-0.9.2.jar with libthrift-0.9.1.jar and libfb303-0.9.1.jar respectively.
-
-### Step3: Use Connector in Spark
-#### 5.2.1.1 Local Mode
+<a id="3-quick-start"></a>
+## 3. Quick Start
+<a id="local-mode"></a>
+### Local Mode
Start Spark with TsFile-Spark-Connector in local mode:
```
-./<spark-shell-path> --jars tsfile-<tsfile-version>.jar,tsfile-spark-connector-<connector-version>.jar
+./<spark-shell-path> --jars tsfile-spark-connector.jar,tsfile-0.8.0-SNAPSHOT-jar-with-dependencies.jar
```
+
Note:
* \<spark-shell-path> is the real path of your spark-shell.
-* \<tsfile-version> is the tsfile version.
-* \<connector-version> is the TsFile-Spark-Connector version. Note that, the version of TsFile-Spark-Connector and TsFile should be correspondence.
* Multiple jar packages are separated by commas without any spaces.
* See https://github.com/apache/incubator-iotdb/tree/master/tsfile for how to get TsFile.
-#### 5.2.1.2 Distributed Mode
+
+<a id="distributed-mode"></a>
+### Distributed Mode
Start Spark with TsFile-Spark-Connector in distributed mode (That is, the spark cluster is connected by spark-shell):
```
-. /<spark-shell-path> --jars tsfile-<tsfile-version>.jar,tsfile-spark-connector-<connector-version>.jar --master spark://ip:7077
+. /<spark-shell-path> --jars tsfile-spark-connector.jar,tsfile-0.8.0-SNAPSHOT-jar-with-dependencies.jar --master spark://ip:7077
```
Note:
* \<spark-shell-path> is the real path of your spark-shell.
-* \<tsfile-version> is the tsfile version.
-* \<connector-version> is the TsFile-Spark-Connector version. Note that, the version of TsFile-Spark-Connector and TsFile should be correspondence.
* Multiple jar packages are separated by commas without any spaces.
* See https://github.com/apache/incubator-iotdb/tree/master/tsfile for how to get TsFile.
-## Detail: Conversion between TsFile and Spark
-
-### TsFile Type <-> SparkSQL type
-
-This library uses the following mapping the data type from TsFile to SparkSQL:
+<a id="4-data-type-correspondence"></a>
+## 4. Data Type Correspondence
-| TsFile | SparkSQL|
+| TsFile data type | SparkSQL data type|
| --------------| -------------- |
| BOOLEAN | BooleanType |
| INT32 | IntegerType |
| INT64 | LongType |
| FLOAT | FloatType |
| DOUBLE | DoubleType |
-| ENUMS | StringType |
| TEXT | StringType |
-### TsFile Schema <-> SparkSQL Table Structure
+<a id="5-schema-inference"></a>
+## 5. Schema Inference
+
+The way to display TsFile is dependent on the schema. Take the following TsFile structure as an example: There are three Measurements in the TsFile schema: status, temperature, and hardware. The basic information of these three measurements is as follows:
+
+<center>
+<table style="text-align:center">
+ <tr><th colspan="2">Name</th><th colspan="2">Type</th><th colspan="2">Encode</th></tr>
+ <tr><td colspan="2">status</td><td colspan="2">Boolean</td><td colspan="2">PLAIN</td></tr>
+ <tr><td colspan="2">temperature</td><td colspan="2">Float</td><td colspan="2">RLE</td></tr>
+ <tr><td colspan="2">hardware</td><td colspan="2">Text</td><td colspan="2">PLAIN</td></tr>
+</table>
+</center>
+
+The existing data in the TsFile is as follows:
+
+
+<center>
+<table style="text-align:center">
+ <tr><th colspan="4">device:root.ln.wf01.wt01</th><th colspan="4">device:root.ln.wf02.wt02</th></tr>
+ <tr><th colspan="2">status</th><th colspan="2">temperature</th><th colspan="2">hardware</th><th colspan="2">status</th></tr>
+ <tr><th>time</th><th>value</td><th>time</th><th>value</td><th>time</th><th>value</th><th>time</th><th>value</td></tr>
+ <tr><td>1</td><td>True</td><td>1</td><td>2.2</td><td>2</td><td>"aaa"</td><td>1</td><td>True</td></tr>
+ <tr><td>3</td><td>True</td><td>2</td><td>2.2</td><td>4</td><td>"bbb"</td><td>2</td><td>False</td></tr>
+ <tr><td>5</td><td> False </td><td>3</td><td>2.1</td><td>6</td><td>"ccc"</td><td>4</td><td>True</td></tr>
+</table>
+</center>
+
+
+The corresponding SparkSQL table is as follows:
+
+| time | root.ln.wf02.wt02.temperature | root.ln.wf02.wt02.status | root.ln.wf02.wt02.hardware | root.ln.wf01.wt01.temperature | root.ln.wf01.wt01.status | root.ln.wf01.wt01.hardware |
+|------|-------------------------------|--------------------------|----------------------------|-------------------------------|--------------------------|----------------------------|
+| 1 | null | true | null | 2.2 | true | null |
+| 2 | null | false | aaa | 2.2 | null | null |
+| 3 | null | null | null | 2.1 | true | null |
+| 4 | null | true | bbb | null | null | null |
+| 5 | null | null | null | null | false | null |
+| 6 | null | null | ccc | null | null | null |
+
+
+<a id="6-scala-api"></a>
+## 6. Scala API
+
+NOTE: Remember to assign necessary read and write permissions in advance.
+
+<a id="example-1-read-from-the-local-file-system"></a>
+### Example 1: read from the local file system
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("test.tsfile")
+df.show
+```
+
+<a id="example-2-read-from-the-hadoop-file-system"></a>
+### Example 2: read from the hadoop file system
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.show
+```
+
+<a id="example-3-read-from-a-specific-directory"></a>
+### Example 3: read from a specific directory
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/usr/hadoop")
+df.show
+```
+
+Note 1: Global time ordering of all TsFiles in a directory is not supported now.
+
+Note 2: Measurements of the same name should have the same schema.
+
+<a id="example-4-query"></a>
+### Example 4: query
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.createOrReplaceTempView("tsfile_table")
+val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1`>0 and `device_1.sensor_2` < 22")
+newDf.show
+```
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.createOrReplaceTempView("tsfile_table")
+val newDf = spark.sql("select count(*) from tsfile_table")
+newDf.show
+```
+
+<a id="example-5-write"></a>
+### Example 5: write
+
+```scala
+import org.apache.iotdb.tsfile._
+
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.show
+df.write.tsfile("hdfs://localhost:9000/output")
+
+val newDf = spark.read.tsfile("hdfs://localhost:9000/output")
+newDf.show
+```
+
+
+<a id="appendix-a-old-design-of-schema-inference"></a>
+## Appendix A: Old Design of Schema Inference
The way to display TsFile is related to TsFile Schema. Take the following TsFile structure as an example: There are three Measurements in the Schema of TsFile: status, temperature, and hardware. The basic info of these three Measurements is as follows:
@@ -148,6 +253,7 @@ The existing data in the file is as follows:
There are two ways to show it out:
+<a id="the-default-way"></a>
#### the default way
Two columns will be created to store the full path of the device: time(LongType) and delta_object(StringType).
@@ -183,6 +289,7 @@ Next, a column is created for each Measurement to store the specific data. The S
</center>
+<a id="unfolding-delta_object-column"></a>
#### unfolding delta_object column
Expand the device column by "." into multiple columns, ignoring the root directory "root". Convenient for richer aggregation operations. If the user wants to use this display way, the parameter "delta\_object\_name" needs to be set in the table creation statement (refer to Example 5 in Section 5.1 of this manual), as in this example, parameter "delta\_object\_name" is set to "root.device.turbine". The number of path layers needs to be one-to-one. At this point, one column is created for [...]
@@ -219,73 +326,6 @@ TsFile-Spark-Connector can display one or more TsFiles as a table in SparkSQL By
The writing process is to write a DataFrame as one or more TsFiles. By default, two columns need to be included: time and delta_object. The rest of the columns are used as Measurement. If user wants to write the second table structure back to TsFile, user can set the "delta\_object\_name" parameter(refer to Section 5.1 of Section 5.1 of this manual).
-## Example
-
-The path of 'test.tsfile' used in the following examples is "data/test.tsfile". Please upload 'test.tsfile' to hdfs in advance and the directory is "/test.tsfile".
-
-### 5.1 Scala API
-
-* **Example 1**
-
- ```scala
- import cn.edu.tsinghua.tsfile._
-
- //read data in TsFile and create a table
- val df = spark.read.tsfile("/test.tsfile")
- df.createOrReplaceTempView("tsfile_table")
-
- //query with filter
- val newDf = spark.sql("select * from tsfile_table where temperature > 1.2").cache()
-
- newDf.show()
- ```
-
-* **Example 2**
-
- ```scala
- val df = spark.read
- .format("cn.edu.tsinghua.tsfile")
- .load("/test.tsfile ")
- df.filter("time < 10").show()
- ```
-
-* **Example 3**
-
- ```scala
- //create a table in SparkSQL and build relation with a TsFile
- spark.sql("create temporary view tsfile_table using cn.edu.tsinghua.tsfile options(path = \"test.ts\")")
-
- spark.sql("select * from tsfile_table where temperature > 1.2").show()
- ```
-
-* **Example 4(using options to read)**
-
- ```scala
- import cn.edu.tsinghua.tsfile._
-
- val df = spark.read.option("delta_object_name", "root.group.field.device").tsfile("/test.tsfile")
-
- //create a table in SparkSQL and build relation with a TsFile
- df.createOrReplaceTempView("tsfile_table")
-
- spark.sql("select * from tsfile_table where device = 'wt01' and field = 'wf01' and group = 'ln' and time < 10").show()
- ```
-
-* **Example 5(write)**
-
- ```scala
- import cn.edu.tsinghua.tsfile._
-
- val df = spark.read.tsfile("/test.tsfile").write.tsfile("/out")
- ```
-
-* **Example 6(using options to write)**
-
- ```scala
- import cn.edu.tsinghua.tsfile._
-
- val df = spark.read.option("delta_object_name", "root.group.field.device").tsfile("/test.tsfile")
-
- df.write.option("delta_object_name", "root.group.field.device").tsfile("/out")
- ```
-
+<a id="appendix-b-old-note"></a>
+## Appendix B: Old Note
+NOTE: Check the jar packages in the root directory of your Spark and replace libthrift-0.9.2.jar and libfb303-0.9.2.jar with libthrift-0.9.1.jar and libfb303-0.9.1.jar respectively.
diff --git a/pom.xml b/pom.xml
index c38f220..d8544b9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -49,7 +49,7 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.assembly.version>2.5.5</maven.assembly.version>
- <scala.version>2.0.1</scala.version>
+ <scala.version>2.11.8</scala.version>
<hadoop.version>2.7.3</hadoop.version>
<junit.version>4.12</junit.version>
<slf4j.version>1.7.12</slf4j.version>
@@ -135,8 +135,8 @@
<module>service-rpc</module>
<module>iotdb-cli</module>
<module>example</module>
- <!--<module>hadoop</module>-->
- <!--<module>spark</module>-->
+ <!-- <module>hadoop</module> -->
+ <module>spark</module>
</modules>
<build>
<pluginManagement>
diff --git a/spark/README.md b/spark/README.md
index 2a82c37..3f88d4e 100644
--- a/spark/README.md
+++ b/spark/README.md
@@ -19,204 +19,313 @@
-->
-# tsfile-spark-connector
-Used to read and write(developing) tsfile in spark.
+<!-- TOC -->
-将一个或多个TsFile展示成SparkSQL中的一张表。允许指定单个目录,或使用通配符匹配多个目录。如果是多个TsFile,schema将保留各个TsFile中sensor的并集。
+- [TsFile-Spark-Connector User Guide](#tsfile-spark-connector-user-guide)
+ - [1. About TsFile-Spark-Connector](#1-about-tsfile-spark-connector)
+ - [2. System Requirements](#2-system-requirements)
+ - [3. Quick Start](#3-quick-start)
+ - [Local Mode](#local-mode)
+ - [Distributed Mode](#distributed-mode)
+ - [4. Data Type Correspondence](#4-data-type-correspondence)
+ - [5. Schema Inference](#5-schema-inference)
+ - [6. Scala API](#6-scala-api)
+ - [Example 1: read from the local file system](#example-1-read-from-the-local-file-system)
+ - [Example 2: read from the hadoop file system](#example-2-read-from-the-hadoop-file-system)
+ - [Example 3: read from a specific directory](#example-3-read-from-a-specific-directory)
+ - [Example 4: query](#example-4-query)
+ - [Example 5: write](#example-5-write)
+ - [Appendix A: Old Design of Schema Inference](#appendix-a-old-design-of-schema-inference)
+ - [the default way](#the-default-way)
+ - [unfolding delta_object column](#unfolding-delta_object-column)
+ - [Appendix B: Old Note](#appendix-b-old-note)
+<!-- /TOC -->
-## 1. dependency
+<a id="tsfile-spark-connector-user-guide"></a>
+# TsFile-Spark-Connector User Guide
-https://github.com/thulab/tsfile.git
+<a id="1-about-tsfile-spark-connector"></a>
+## 1. About TsFile-Spark-Connector
+TsFile-Spark-Connector implements the support of Spark for external data sources of Tsfile type. This enables users to read, write and query Tsfile by Spark.
-## 2. versions
+With this connector, you can
+* load a single TsFile, from either the local file system or hdfs, into Spark
+* load all files in a specific directory, from either the local file system or hdfs, into Spark
+* write data from Spark into TsFile
-The versions required for Spark and Java are as follow:
+<a id="2-system-requirements"></a>
+## 2. System Requirements
-| Spark Version | Scala Version | Java Version | TsFile |
-| ------------- | ------------- | ------------ |------------ |
-| `2.0+` | `2.11` | `1.8` | `0.4.0`|
+|Spark Version | Scala Version | Java Version | TsFile |
+|------------- | ------------- | ------------ |------------ |
+| `2.0.1` | `2.11.8` | `1.8` | `0.8.0-SNAPSHOT`|
-ATTENTION: Please check the jar packages in the root directory of your spark and replace libthrift-0.9.2.jar and libfb303-0.9.2.jar with libthrift-0.9.1.jar and libfb303-0.9.1.jar respectively.
+> Note: For more information about how to download and use TsFile, please see the following link: https://github.com/apache/incubator-iotdb/tree/master/tsfile.
-## 3. TsFile Type <=> SparkSQL type
+<a id="3-quick-start"></a>
+## 3. Quick Start
+<a id="local-mode"></a>
+### Local Mode
-This library uses the following mapping the data type from TsFile to SparkSQL:
+Start Spark with TsFile-Spark-Connector in local mode:
-| TsFile | SparkSQL|
+```
+./<spark-shell-path> --jars tsfile-spark-connector.jar,tsfile-0.8.0-SNAPSHOT-jar-with-dependencies.jar
+```
+
+Note:
+
+* \<spark-shell-path> is the real path of your spark-shell.
+* Multiple jar packages are separated by commas without any spaces.
+* See https://github.com/apache/incubator-iotdb/tree/master/tsfile for how to get TsFile.
+
+
+<a id="distributed-mode"></a>
+### Distributed Mode
+
+Start Spark with TsFile-Spark-Connector in distributed mode (That is, the spark cluster is connected by spark-shell):
+
+```
+. /<spark-shell-path> --jars tsfile-spark-connector.jar,tsfile-0.8.0-SNAPSHOT-jar-with-dependencies.jar --master spark://ip:7077
+```
+
+Note:
+
+* \<spark-shell-path> is the real path of your spark-shell.
+* Multiple jar packages are separated by commas without any spaces.
+* See https://github.com/apache/incubator-iotdb/tree/master/tsfile for how to get TsFile.
+
+<a id="4-data-type-correspondence"></a>
+## 4. Data Type Correspondence
+
+| TsFile data type | SparkSQL data type|
| --------------| -------------- |
+| BOOLEAN | BooleanType |
| INT32 | IntegerType |
| INT64 | LongType |
| FLOAT | FloatType |
| DOUBLE | DoubleType |
-| BYTE_ARRAY | StringType |
+| TEXT | StringType |
+<a id="5-schema-inference"></a>
+## 5. Schema Inference
-## 4. TsFile Schema <-> SparkSQL Table Structure
+The way to display TsFile is dependent on the schema. Take the following TsFile structure as an example: There are three Measurements in the TsFile schema: status, temperature, and hardware. The basic information of these three measurements is as follows:
+
+<center>
+<table style="text-align:center">
+ <tr><th colspan="2">Name</th><th colspan="2">Type</th><th colspan="2">Encode</th></tr>
+ <tr><td colspan="2">status</td><td colspan="2">Boolean</td><td colspan="2">PLAIN</td></tr>
+ <tr><td colspan="2">temperature</td><td colspan="2">Float</td><td colspan="2">RLE</td></tr>
+ <tr><td colspan="2">hardware</td><td colspan="2">Text</td><td colspan="2">PLAIN</td></tr>
+</table>
+</center>
+
+The existing data in the TsFile is as follows:
-The set of time-series data in section "Time-series Data" is used here to illustrate the mapping from TsFile Schema to SparkSQL Table Stucture.
<center>
<table style="text-align:center">
- <tr><th colspan="6">delta_object:root.car.turbine1</th></tr>
- <tr><th colspan="2">sensor_1</th><th colspan="2">sensor_2</th><th colspan="2">sensor_3</th></tr>
- <tr><th>time</th><th>value</td><th>time</th><th>value</td><th>time</th><th>value</td>
- <tr><td>1</td><td>1.2</td><td>1</td><td>20</td><td>2</td><td>50</td></tr>
- <tr><td>3</td><td>1.4</td><td>2</td><td>20</td><td>4</td><td>51</td></tr>
- <tr><td>5</td><td>1.1</td><td>3</td><td>21</td><td>6</td><td>52</td></tr>
- <tr><td>7</td><td>1.8</td><td>4</td><td>20</td><td>8</td><td>53</td></tr>
+ <tr><th colspan="4">device:root.ln.wf01.wt01</th><th colspan="4">device:root.ln.wf02.wt02</th></tr>
+ <tr><th colspan="2">status</th><th colspan="2">temperature</th><th colspan="2">hardware</th><th colspan="2">status</th></tr>
+ <tr><th>time</th><th>value</td><th>time</th><th>value</td><th>time</th><th>value</th><th>time</th><th>value</td></tr>
+ <tr><td>1</td><td>True</td><td>1</td><td>2.2</td><td>2</td><td>"aaa"</td><td>1</td><td>True</td></tr>
+ <tr><td>3</td><td>True</td><td>2</td><td>2.2</td><td>4</td><td>"bbb"</td><td>2</td><td>False</td></tr>
+ <tr><td>5</td><td> False </td><td>3</td><td>2.1</td><td>6</td><td>"ccc"</td><td>4</td><td>True</td></tr>
</table>
-<span>A set of time-series data</span>
</center>
-### 4.1. using delta_object as reserved column
-There are two reserved columns in Spark SQL Table:
+The corresponding SparkSQL table is as follows:
-- `time` : Timestamp, LongType
-- `delta_object` : Delta_object ID, StringType
+| time | root.ln.wf02.wt02.temperature | root.ln.wf02.wt02.status | root.ln.wf02.wt02.hardware | root.ln.wf01.wt01.temperature | root.ln.wf01.wt01.status | root.ln.wf01.wt01.hardware |
+|------|-------------------------------|--------------------------|----------------------------|-------------------------------|--------------------------|----------------------------|
+| 1 | null | true | null | 2.2 | true | null |
+| 2 | null | false | aaa | 2.2 | null | null |
+| 3 | null | null | null | 2.1 | true | null |
+| 4 | null | true | bbb | null | null | null |
+| 5 | null | null | null | null | false | null |
+| 6 | null | null | ccc | null | null | null |
+
+
+<a id="6-scala-api"></a>
+## 6. Scala API
+
+NOTE: Remember to assign necessary read and write permissions in advance.
+
+<a id="example-1-read-from-the-local-file-system"></a>
+### Example 1: read from the local file system
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("test.tsfile")
+df.show
+```
+
+<a id="example-2-read-from-the-hadoop-file-system"></a>
+### Example 2: read from the hadoop file system
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.show
+```
+
+<a id="example-3-read-from-a-specific-directory"></a>
+### Example 3: read from a specific directory
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/usr/hadoop")
+df.show
+```
+
+Note 1: Global time ordering of all TsFiles in a directory is not supported now.
+
+Note 2: Measurements of the same name should have the same schema.
-The SparkSQL Table Structure is as follow:
+<a id="example-4-query"></a>
+### Example 4: query
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.createOrReplaceTempView("tsfile_table")
+val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1`>0 and `device_1.sensor_2` < 22")
+newDf.show
+```
+
+```scala
+import org.apache.iotdb.tsfile._
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.createOrReplaceTempView("tsfile_table")
+val newDf = spark.sql("select count(*) from tsfile_table")
+newDf.show
+```
+
+<a id="example-5-write"></a>
+### Example 5: write
+
+```scala
+import org.apache.iotdb.tsfile._
+
+val df = spark.read.tsfile("hdfs://localhost:9000/test.tsfile")
+df.show
+df.write.tsfile("hdfs://localhost:9000/output")
+
+val newDf = spark.read.tsfile("hdfs://localhost:9000/output")
+newDf.show
+```
+
+
+<a id="appendix-a-old-design-of-schema-inference"></a>
+## Appendix A: Old Design of Schema Inference
+
+The way to display TsFile is related to TsFile Schema. Take the following TsFile structure as an example: There are three Measurements in the Schema of TsFile: status, temperature, and hardware. The basic info of these three Measurements is as follows:
<center>
- <table style="text-align:center">
- <tr><th>time(LongType)</th><th> delta_object(StringType)</th><th>sensor_1(FloatType)</th><th>sensor_2(IntType)</th><th>sensor_3(IntType)</th></tr>
- <tr><td>1</td><td> root.car.turbine1 </td><td>1.2</td><td>20</td><td>null</td></tr>
- <tr><td>2</td><td> root.car.turbine1 </td><td>null</td><td>20</td><td>50</td></tr>
- <tr><td>3</td><td> root.car.turbine1 </td><td>1.4</td><td>21</td><td>null</td></tr>
- <tr><td>4</td><td> root.car.turbine1 </td><td>null</td><td>20</td><td>51</td></tr>
- <tr><td>5</td><td> root.car.turbine1 </td><td>1.1</td><td>null</td><td>null</td></tr>
- <tr><td>6</td><td> root.car.turbine1 </td><td>null</td><td>null</td><td>52</td></tr>
- <tr><td>7</td><td> root.car.turbine1 </td><td>1.8</td><td>null</td><td>null</td></tr>
- <tr><td>8</td><td> root.car.turbine1 </td><td>null</td><td>null</td><td>53</td></tr>
- </table>
+<table style="text-align:center">
+ <tr><th colspan="2">Name</th><th colspan="2">Type</th><th colspan="2">Encode</th></tr>
+ <tr><td colspan="2">status</td><td colspan="2">Boolean</td><td colspan="2">PLAIN</td></tr>
+ <tr><td colspan="2">temperature</td><td colspan="2">Float</td><td colspan="2">RLE</td></tr>
+ <tr><td colspan="2">hardware</td><td colspan="2">Text</td><td colspan="2">PLAIN</td></tr>
+</table>
+<span>Basic info of Measurements</span>
+</center>
+
+The existing data in the file is as follows:
+<center>
+<table style="text-align:center">
+ <tr><th colspan="4">delta\_object:root.ln.wf01.wt01</th><th colspan="4">delta\_object:root.ln.wf02.wt02</th><th colspan="4">delta\_object:root.sgcc.wf03.wt01</th></tr>
+ <tr><th colspan="2">status</th><th colspan="2">temperature</th><th colspan="2">hardware</th><th colspan="2">status</th><th colspan="2">status</th><th colspan="2">temperature</th></tr>
+ <tr><th>time</th><th>value</td><th>time</th><th>value</td><th>time</th><th>value</th><th>time</th><th>value</td><th>time</th><th>value</td><th>time</th><th>value</th></tr>
+ <tr><td>1</td><td>True</td><td>1</td><td>2.2</td><td>2</td><td>"aaa"</td><td>1</td><td>True</td><td>2</td><td>True</td><td>3</td><td>3.3</td></tr>
+ <tr><td>3</td><td>True</td><td>2</td><td>2.2</td><td>4</td><td>"bbb"</td><td>2</td><td>False</td><td>3</td><td>True</td><td>6</td><td>6.6</td></tr>
+ <tr><td>5</td><td> False </td><td>3</td><td>2.1</td><td>6</td><td>"ccc"</td><td>4</td><td>True</td><td>4</td><td>True</td><td>8</td><td>8.8</td></tr>
+ <tr><td>7</td><td> True </td><td>4</td><td>2.0</td><td>8</td><td>"ddd"</td><td>5</td><td>False</td><td>6</td><td>True</td><td>9</td><td>9.9</td></tr>
+</table>
+<span>A set of time-series data</span>
</center>
+There are two ways to show it out:
+
+<a id="the-default-way"></a>
+#### the default way
-### 4.2. unfolding delta_object column
+Two columns will be created to store the full path of the device: time(LongType) and delta_object(StringType).
+
+- `time` : Timestamp, LongType
+- `delta_object` : Delta_object ID, StringType
-If you want to unfold the delta_object column into multi columns you should add an option when read and write:
+Next, a column is created for each Measurement to store the specific data. The SparkSQL table structure is as follows:
-e.g.
+<center>
+ <table style="text-align:center">
+ <tr><th>time(LongType)</th><th> delta\_object(StringType)</th><th>status(BooleanType)</th><th>temperature(FloatType)</th><th>hardware(StringType)</th></tr>
+ <tr><td>1</td><td> root.ln.wf01.wt01 </td><td>True</td><td>2.2</td><td>null</td></tr>
+ <tr><td>1</td><td> root.ln.wf02.wt02 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>2</td><td> root.ln.wf01.wt01 </td><td>null</td><td>2.2</td><td>null</td></tr>
+ <tr><td>2</td><td> root.ln.wf02.wt02 </td><td>False</td><td>null</td><td>"aaa"</td></tr>
+ <tr><td>2</td><td> root.sgcc.wf03.wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>3</td><td> root.ln.wf01.wt01 </td><td>True</td><td>2.1</td><td>null</td></tr>
+ <tr><td>3</td><td> root.sgcc.wf03.wt01 </td><td>True</td><td>3.3</td><td>null</td></tr>
+ <tr><td>4</td><td> root.ln.wf01.wt01 </td><td>null</td><td>2.0</td><td>null</td></tr>
+ <tr><td>4</td><td> root.ln.wf02.wt02 </td><td>True</td><td>null</td><td>"bbb"</td></tr>
+ <tr><td>4</td><td> root.sgcc.wf03.wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> root.ln.wf01.wt01 </td><td>False</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> root.ln.wf02.wt02 </td><td>False</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> root.sgcc.wf03.wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>6</td><td> root.ln.wf02.wt02 </td><td>null</td><td>null</td><td>"ccc"</td></tr>
+ <tr><td>6</td><td> root.sgcc.wf03.wt01 </td><td>null</td><td>6.6</td><td>null</td></tr>
+ <tr><td>7</td><td> root.ln.wf01.wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>8</td><td> root.ln.wf02.wt02 </td><td>null</td><td>null</td><td>"ddd"</td></tr>
+ <tr><td>8</td><td> root.sgcc.wf03.wt01 </td><td>null</td><td>8.8</td><td>null</td></tr>
+ <tr><td>9</td><td> root.sgcc.wf03.wt01 </td><td>null</td><td>9.9</td><td>null</td></tr>
+ </table>
+</center>
-option("delta_object_name" -> "root.device.turbine")
-The "delta_object_name" is reserved key.
+<a id="unfolding-delta_object-column"></a>
+#### unfolding delta_object column
+Expand the device column by "." into multiple columns, ignoring the root directory "root". Convenient for richer aggregation operations. If the user wants to use this display way, the parameter "delta\_object\_name" needs to be set in the table creation statement (refer to Example 5 in Section 5.1 of this manual), as in this example, parameter "delta\_object\_name" is set to "root.device.turbine". The number of path layers needs to be one-to-one. At this point, one column is created for [...]
Then The SparkSQL Table Structure is as follow:
<center>
<table style="text-align:center">
- <tr><th>time(LongType)</th><th> device(StringType)</th><th> turbine(StringType)</th><th>sensor_1(FloatType)</th><th>sensor_2(IntType)</th><th>sensor_3(IntType)</th></tr>
- <tr><td>1</td><td> car </td><td> turbine1 </td><td>1.2</td><td>20</td><td>null</td></tr>
- <tr><td>2</td><td> car </td><td> turbine1 </td><td>null</td><td>20</td><td>50</td></tr>
- <tr><td>3</td><td> car </td><td> turbine1 </td><td>1.4</td><td>21</td><td>null</td></tr>
- <tr><td>4</td><td> car </td><td> turbine1 </td><td>null</td><td>20</td><td>51</td></tr>
- <tr><td>5</td><td> car </td><td> turbine1 </td><td>1.1</td><td>null</td><td>null</td></tr>
- <tr><td>6</td><td> car </td><td> turbine1 </td><td>null</td><td>null</td><td>52</td></tr>
- <tr><td>7</td><td> car </td><td> turbine1 </td><td>1.8</td><td>null</td><td>null</td></tr>
- <tr><td>8</td><td> car </td><td> turbine1 </td><td>null</td><td>null</td><td>53</td></tr>
+ <tr><th>time(LongType)</th><th> group(StringType)</th><th> field(StringType)</th><th> device(StringType)</th><th>status(BooleanType)</th><th>temperature(FloatType)</th><th>hardware(StringType)</th></tr>
+ <tr><td>1</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>True</td><td>2.2</td><td>null</td></tr>
+ <tr><td>1</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>2</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>null</td><td>2.2</td><td>null</td></tr>
+ <tr><td>2</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>False</td><td>null</td><td>"aaa"</td></tr>
+ <tr><td>2</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>3</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>True</td><td>2.1</td><td>null</td></tr>
+ <tr><td>3</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>True</td><td>3.3</td><td>null</td></tr>
+ <tr><td>4</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>null</td><td>2.0</td><td>null</td></tr>
+ <tr><td>4</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>True</td><td>null</td><td>"bbb"</td></tr>
+ <tr><td>4</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>False</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>False</td><td>null</td><td>null</td></tr>
+ <tr><td>5</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>6</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>null</td><td>null</td><td>"ccc"</td></tr>
+ <tr><td>6</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>null</td><td>6.6</td><td>null</td></tr>
+ <tr><td>7</td><td> ln </td><td> wf01 </td><td> wt01 </td><td>True</td><td>null</td><td>null</td></tr>
+ <tr><td>8</td><td> ln </td><td> wf02 </td><td> wt02 </td><td>null</td><td>null</td><td>"ddd"</td></tr>
+ <tr><td>8</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>null</td><td>8.8</td><td>null</td></tr>
+ <tr><td>9</td><td> sgcc </td><td> wf03 </td><td> wt01 </td><td>null</td><td>9.9</td><td>null</td></tr>
</table>
</center>
+TsFile-Spark-Connector can display one or more TsFiles as a table in SparkSQL By SparkSQL. It also allows users to specify a single directory or use wildcards to match multiple directories. If there are multiple TsFiles, the union of the measurements in all TsFiles will be retained in the table, and the measurement with the same name will have the same data type by default. Note that if there is a situation with the same name but different data types, TsFile-Spark-Connector will not guar [...]
-Then you can group by any level in delta_object. And then with the same option you can write this dataframe to TsFile.
+The writing process is to write a DataFrame as one or more TsFiles. By default, two columns need to be included: time and delta_object. The rest of the columns are used as Measurement. If user wants to write the second table structure back to TsFile, user can set the "delta\_object\_name" parameter(refer to Section 5.1 of Section 5.1 of this manual).
-## 5. Building
-
-```
-mvn clean scala:compile compile package
-```
-
-
-## 6. Examples
-
-The path of 'test.tsfile' used in the following examples is "data/test.tsfile". Please upload 'test.tsfile' to hdfs in advance and the directory is "/test.tsfile".
-
-
-### 6.1 Scala API
-
-* **Example 1**
-
- ```scala
- import org.apache.iotdb.tsfile._
-
- //read data in TsFile and create a table
- val df = spark.read.tsfile("/test.tsfile")
- df.createOrReplaceTempView("tsfile_table")
-
- //query with filter
- val newDf = spark.sql("select * from tsfile_table where s1 > 1.2").cache()
-
- newDf.show()
- ```
-
-* **Example 2**
-
- ```scala
- val df = spark.read
- .format("org.apache.iotdb.tsfile")
- .load("/test.tsfile ")
- df.filter("time < 10").show()
- ```
-
-* **Example 3**
-
- ```scala
- //create a table in SparkSQL and build relation with a TsFile
- spark.sql("create temporary view tsfile_table using org.apache.iotdb.tsfile options(path = \"test.ts\")")
-
- spark.sql("select * from tsfile_table where s1 > 1.2").show()
- ```
-
-* **Example 4(using options to read)**
-
- ```scala
- import org.apache.iotdb.tsfile._
-
- val df = spark.read.option("delta_object_name", "root.device.turbine").tsfile("/test.tsfile")
-
- //create a table in SparkSQL and build relation with a TsFile
- df.createOrReplaceTempView("tsfile_table")
-
- spark.sql("select * from tsfile_table where turbine = 'd1' and device = 'car' and time < 10").show()
- ```
-
-* **Example 5(write)**
-
- ```scala
- import org.apache.iotdb.tsfile._
-
- val df = spark.read.tsfile("/test.tsfile").write.tsfile("/out")
- ```
-
-* **Example 6(using options to write)**
-
- ```scala
- import org.apache.iotdb.tsfile._
-
- val df = spark.read.option("delta_object_name", "root.device.turbine").tsfile("/test.tsfile")
-
- df.write.option("delta_object_name", "root.device.turbine").tsfile("/out")
- ```
-
-
-### 6.2 spark-shell
-#### 6.2.1 Start Spark
-##### 6.2.1.1 Local Mode
-```
-./spark-2.0.1-bin-hadoop2.7/bin/spark-shell --jars tsfile-0.4.0.jar,tsfile-spark-connector-0.4.0.jar
-```
-ATTENTION:
-* Please replace "spark-2.0.1-bin-hadoop2.7/bin/spark-shell" with the real path of your spark-shell.
-* Multiple jar packages are separated by commas without any spaces.
-* The latest version used is v0.4.0.
-##### 6.2.1.2 Distributed Mode
-```
-. /spark-2.0.1-bin-hadoop2.7/bin/spark-shell --jars tsfile-0.4.0.jar,tsfile-spark-connector-0.4.0.jar --master spark://ip:7077
-```
\ No newline at end of file
+<a id="appendix-b-old-note"></a>
+## Appendix B: Old Note
+NOTE: Check the jar packages in the root directory of your Spark and replace libthrift-0.9.2.jar and libfb303-0.9.2.jar with libthrift-0.9.1.jar and libfb303-0.9.1.jar respectively.
diff --git a/spark/pom.xml b/spark/pom.xml
index 86346bf..770ae0e 100644
--- a/spark/pom.xml
+++ b/spark/pom.xml
@@ -56,12 +56,12 @@
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
- <version>2.11.8</version>
+ <version>${scala.version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.11</artifactId>
- <version>3.0.0</version>
+ <version>3.0.5</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -89,9 +89,6 @@
</goals>
</execution>
</executions>
- <configuration>
- <scalaVersion>2.11.8</scalaVersion>
- </configuration>
</plugin>
</plugins>
</build>
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/CreateTSFile.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/CreateTSFile.java
deleted file mode 100755
index ee417b7..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/io/CreateTSFile.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * 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.iotdb.tsfile.io;
-
-import java.io.File;
-
-import com.alibaba.fastjson.JSONArray;
-import com.alibaba.fastjson.JSONObject;
-import org.apache.iotdb.tsfile.common.conf.TSFileConfig;
-import org.apache.iotdb.tsfile.common.conf.TSFileDescriptor;
-import org.apache.iotdb.tsfile.common.constant.JsonFormatConstant;
-import org.apache.iotdb.tsfile.common.utils.TsRandomAccessFileWriter;
-import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
-import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
-import org.apache.iotdb.tsfile.timeseries.basis.TsFile;
-
-/**
- * create a TSFile for test
- *
- */
-public class CreateTSFile {
-
- public void createTSFile1(String tsfilePath) throws Exception {
- File file = new File(tsfilePath);
- if (file.exists()) {
- file.delete();
- }
-
- JSONObject jsonSchema = generateSchema1();
- TsRandomAccessFileWriter output = new TsRandomAccessFileWriter(new File(tsfilePath));
- TsFile tsFile = new TsFile(output, jsonSchema);
-
- tsFile.writeLine("root.car.d1,1, s1, 1, s2, 10, s3, 100.1");
- tsFile.writeLine("root.car.d1,2, s1, 2, s2, 20, s3, 200.2, s4, 0.2, s5, PASS");
- tsFile.writeLine("root.car.d1,3, s1, 3, s2, 30, s3, 200.3, s4, 0.3, s5, UNPASS");
- tsFile.writeLine("root.car.d1,4, s1, 4, s2, 40, s3, 200.4, s4, 0.4");
-
- tsFile.writeLine("root.car.d2,5, s1, 5, s2, 50, s3, 200.5, s4, 0.5");
- tsFile.writeLine("root.car.d2,6, s1, 6, s2, 60, s3, 200.6, s4, 0.6");
- tsFile.writeLine("root.car.d2,7, s1, 7, s2, 70, s3, 200.7, s4, 0.7");
- tsFile.writeLine("root.car.d2,8, s1, 8, s2, 80, s3, 200.8, s4, 0.8");
- tsFile.close();
- }
-
- public void createTSFile2(String tsfilePath) throws Exception {
- File file = new File(tsfilePath);
- if (file.exists()) {
- file.delete();
- }
-
- JSONObject jsonSchema = generateSchema2();
- TsRandomAccessFileWriter output = new TsRandomAccessFileWriter(new File(tsfilePath));
- TsFile tsFile = new TsFile(output, jsonSchema);
-
- tsFile.writeLine("root.car.d1,1, s1, 1");
- tsFile.writeLine("root.car.d1,2, s1, 2");
- tsFile.writeLine("root.car.d1,3, s1, 3");
- tsFile.writeLine("root.car.d1,4, s1, 4");
- tsFile.writeLine("root.car.d2,5, s1, 5");
- tsFile.writeLine("root.car.d2,6, s1, 6");
- tsFile.writeLine("root.car.d2,7, s1, 7");
- tsFile.writeLine("root.car.d2,8, s1, 8");
- tsFile.close();
- }
-
- private JSONObject generateSchema1() {
- TSFileConfig conf = TSFileDescriptor.getInstance().getConfig();
- JSONObject s1 = new JSONObject();
- s1.put(JsonFormatConstant.MEASUREMENT_UID, "s1");
- s1.put(JsonFormatConstant.DATA_TYPE, TSDataType.INT32.toString());
- s1.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONObject s2 = new JSONObject();
- s2.put(JsonFormatConstant.MEASUREMENT_UID, "s2");
- s2.put(JsonFormatConstant.DATA_TYPE, TSDataType.INT64.toString());
- s2.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONObject s3 = new JSONObject();
- s3.put(JsonFormatConstant.MEASUREMENT_UID, "s3");
- s3.put(JsonFormatConstant.DATA_TYPE, TSDataType.FLOAT.toString());
- s3.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONObject s4 = new JSONObject();
- s4.put(JsonFormatConstant.MEASUREMENT_UID, "s4");
- s4.put(JsonFormatConstant.DATA_TYPE, TSDataType.DOUBLE.toString());
- s4.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONObject s5 = new JSONObject();
- s5.put(JsonFormatConstant.MEASUREMENT_UID, "s5");
- s5.put(JsonFormatConstant.DATA_TYPE, TSDataType.TEXT.toString());
- s5.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.PLAIN.toString());
-
- JSONArray measureGroup = new JSONArray();
- measureGroup.add(s1);
- measureGroup.add(s2);
- measureGroup.add(s3);
- measureGroup.add(s4);
- measureGroup.add(s5);
-
- JSONObject jsonSchema = new JSONObject();
- jsonSchema.put(JsonFormatConstant.DELTA_TYPE, "test_type");
- jsonSchema.put(JsonFormatConstant.JSON_SCHEMA, measureGroup);
- return jsonSchema;
- }
-
- private JSONObject generateSchema2() {
- TSFileConfig conf = TSFileDescriptor.getInstance().getConfig();
- JSONObject s1 = new JSONObject();
- s1.put(JsonFormatConstant.MEASUREMENT_UID, "s1");
- s1.put(JsonFormatConstant.DATA_TYPE, TSDataType.INT32.toString());
- s1.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONObject s2 = new JSONObject();
- s2.put(JsonFormatConstant.MEASUREMENT_UID, "s2");
- s2.put(JsonFormatConstant.DATA_TYPE, TSDataType.INT64.toString());
- s2.put(JsonFormatConstant.MEASUREMENT_ENCODING,
- TSEncoding.RLE.toString());
-
- JSONArray measureGroup = new JSONArray();
- measureGroup.put(s1);
- measureGroup.put(s2);
-
- JSONObject jsonSchema = new JSONObject();
- jsonSchema.put(JsonFormatConstant.DELTA_TYPE, "test_type");
- jsonSchema.put(JsonFormatConstant.JSON_SCHEMA, measureGroup);
- return jsonSchema;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInput.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInput.java
new file mode 100644
index 0000000..fc14fad
--- /dev/null
+++ b/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInput.java
@@ -0,0 +1,147 @@
+/**
+ * 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.iotdb.tsfile.io;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.ChecksumFileSystem;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.iotdb.tsfile.read.reader.TsFileInput;
+
+public class HDFSInput implements TsFileInput {
+
+ private FSDataInputStream fsDataInputStream;
+ private FileStatus fileStatus;
+ private boolean byteBufferReadable;
+
+ public HDFSInput(String filePath) throws IOException {
+
+ this(filePath, new Configuration());
+ }
+
+ public HDFSInput(String filePath, Configuration configuration) throws IOException {
+
+ this(new Path(filePath), configuration);
+ }
+
+ public HDFSInput(Path path, Configuration configuration) throws IOException {
+ FileSystem fs = path.getFileSystem(configuration);
+ if (fs instanceof ChecksumFileSystem) {
+ byteBufferReadable = false;
+ } else {
+ byteBufferReadable = true;
+ }
+ fsDataInputStream = fs.open(path);
+ fileStatus = fs.getFileStatus(path);
+ }
+
+ @Override
+ public long size() {
+ return fileStatus.getLen();
+ }
+
+ @Override
+ public long position() throws IOException {
+ return fsDataInputStream.getPos();
+ }
+
+ @Override
+ public TsFileInput position(long newPosition) throws IOException {
+ fsDataInputStream.seek(newPosition);
+ return this;
+ }
+
+ @Override
+ public int read(ByteBuffer dst) throws IOException {
+ int res;
+ if (byteBufferReadable) {
+ res = fsDataInputStream.read(dst);
+ } else {
+ byte[] bytes = new byte[dst.remaining()];
+ res = fsDataInputStream.read(bytes);
+ dst.put(bytes);
+ }
+ return res;
+ }
+
+ @Override
+ public int read(ByteBuffer dst, long position) throws IOException {
+ if (position < 0) {
+ throw new IllegalArgumentException("position must be non-negative");
+ }
+
+ if (position >= this.size()) {
+ return -1;
+ }
+
+ long srcPosition = fsDataInputStream.getPos();
+
+ fsDataInputStream.seek(position);
+
+ int res;
+ if (byteBufferReadable) {
+ res = fsDataInputStream.read(dst);
+ } else {
+ byte[] bytes = new byte[dst.remaining()];
+ res = fsDataInputStream.read(bytes);
+ dst.put(bytes);
+ }
+
+ fsDataInputStream.seek(srcPosition);
+
+ return res;
+ }
+
+ @Override
+ public int read() throws IOException {
+ throw new IOException("Not support");
+ }
+
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ throw new IOException("Not support");
+ }
+
+ @Override
+ public FileChannel wrapAsFileChannel() throws IOException {
+ throw new IOException("Not support");
+ }
+
+ @Override
+ public InputStream wrapAsInputStream() throws IOException {
+ return fsDataInputStream;
+ }
+
+ @Override
+ public void close() throws IOException {
+ fsDataInputStream.close();
+ }
+
+ @Override
+ public int readInt() throws IOException {
+ throw new IOException("Not support");
+ }
+
+}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInputStream.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInputStream.java
deleted file mode 100644
index 8d67fe6..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSInputStream.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * 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.iotdb.tsfile.io;
-
-import java.io.IOException;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataInputStream;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.iotdb.tsfile.common.utils.ITsRandomAccessFileReader;
-
-/**
- * This class is used to wrap the {@link}FSDataInputStream and implement the
- * interface {@link}TSRandomAccessFileReader.
- *
- * @author liukun
- */
-public class HDFSInputStream implements ITsRandomAccessFileReader {
-
- private FSDataInputStream fsDataInputStream;
- private FileStatus fileStatus;
-
- public HDFSInputStream(String filePath) throws IOException {
-
- this(filePath, new Configuration());
- }
-
- public HDFSInputStream(String filePath, Configuration configuration) throws IOException {
-
- this(new Path(filePath), configuration);
- }
-
- public HDFSInputStream(Path path, Configuration configuration) throws IOException {
-
- FileSystem fs = FileSystem.get(configuration);
- fsDataInputStream = fs.open(path);
- fileStatus = fs.getFileStatus(path);
- }
-
- public void seek(long offset) throws IOException {
-
- fsDataInputStream.seek(offset);
- }
-
- public int read() throws IOException {
-
- return fsDataInputStream.read();
- }
-
- public long length() throws IOException {
-
- return fileStatus.getLen();
- }
-
- public int readInt() throws IOException {
-
- return fsDataInputStream.readInt();
- }
-
- public void close() throws IOException {
-
- fsDataInputStream.close();
- }
-
- public long getPos() throws IOException {
-
- return fsDataInputStream.getPos();
- }
-
- /**
- * Read the data into b, and the check the length
- *
- * @param b
- * read the data into
- * @param off
- * the begin offset to read into
- * @param len
- * the length to read into
- */
- public int read(byte[] b, int off, int len) throws IOException {
- if (len < 0) {
- throw new IndexOutOfBoundsException();
- }
- int n = 0;
- while (n < len) {
- int count = fsDataInputStream.read(b, off + n, len - n);
- if (count < 0) {
- throw new IOException("The read length is out of the length of inputstream");
- }
- n += count;
- }
- return n;
- }
-}
\ No newline at end of file
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutputStream.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutput.java
similarity index 67%
rename from spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutputStream.java
rename to spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutput.java
index 9057432..9a18e4a 100644
--- a/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutputStream.java
+++ b/spark/src/main/java/org/apache/iotdb/tsfile/io/HDFSOutput.java
@@ -20,74 +20,74 @@ package org.apache.iotdb.tsfile.io;
import java.io.IOException;
import java.io.OutputStream;
+import java.nio.ByteBuffer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.iotdb.tsfile.common.utils.ITsRandomAccessFileWriter;
+import org.apache.iotdb.tsfile.write.writer.TsFileOutput;
/**
- * This class is used to wrap the {@link}FSDataOutputStream and implement the
- * interface {@link}TSRandomAccessFileWriter
- *
+ * This class is used to wrap the {@link}FSDataOutputStream and implement the interface
+ * {@link}TsFileOutput
*/
-public class HDFSOutputStream implements ITsRandomAccessFileWriter {
+public class HDFSOutput implements TsFileOutput {
private FSDataOutputStream fsDataOutputStream;
- public HDFSOutputStream(String filePath, boolean overwriter) throws IOException {
+ public HDFSOutput(String filePath, boolean overwriter) throws IOException {
this(filePath, new Configuration(), overwriter);
}
- public HDFSOutputStream(String filePath, Configuration configuration, boolean overwriter)
+ public HDFSOutput(String filePath, Configuration configuration, boolean overwriter)
throws IOException {
this(new Path(filePath), configuration, overwriter);
}
- public HDFSOutputStream(Path path, Configuration configuration, boolean overwriter)
+ public HDFSOutput(Path path, Configuration configuration, boolean overwriter)
throws IOException {
-
- FileSystem fsFileSystem = FileSystem.get(configuration);
- fsDataOutputStream = fsFileSystem.create(path, overwriter);
+ FileSystem fs = path.getFileSystem(configuration);
+ fsDataOutputStream = fs.create(path, overwriter);
}
@Override
- public OutputStream getOutputStream() {
+ public void write(byte[] b) throws IOException {
- return fsDataOutputStream;
+ fsDataOutputStream.write(b);
+ }
+
+ public void write(ByteBuffer b) throws IOException {
+ throw new IOException("Not support");
}
@Override
- public long getPos() throws IOException {
+ public long getPosition() throws IOException {
return fsDataOutputStream.getPos();
}
@Override
- public void seek(long offset) throws IOException {
- throw new IOException("Not support");
+ public void close() throws IOException {
+
+ fsDataOutputStream.close();
}
@Override
- public void write(int b) throws IOException {
-
- fsDataOutputStream.write(b);
+ public OutputStream wrapAsStream() throws IOException {
+ return fsDataOutputStream;
}
@Override
- public void write(byte[] b) throws IOException {
-
- fsDataOutputStream.write(b);
+ public void flush() throws IOException {
+ this.fsDataOutputStream.flush();
}
@Override
- public void close() throws IOException {
-
- fsDataOutputStream.close();
+ public void truncate(long position) throws IOException {
+ throw new IOException("Not support");
}
-
}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileOutputFormat.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileOutputFormat.java
index 57faa12..c925561 100644
--- a/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileOutputFormat.java
+++ b/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileOutputFormat.java
@@ -24,7 +24,6 @@ import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
-import org.apache.iotdb.tsfile.write.exception.WriteProcessException;
import org.apache.iotdb.tsfile.write.record.TSRecord;
import org.apache.iotdb.tsfile.write.schema.FileSchema;
@@ -38,14 +37,9 @@ public class TsFileOutputFormat extends FileOutputFormat<NullWritable, TSRecord>
@Override
public RecordWriter<NullWritable, TSRecord> getRecordWriter(TaskAttemptContext job)
- throws IOException, InterruptedException {
+ throws IOException {
Path path = getDefaultWorkFile(job, "");
- try {
- return new TsFileRecordWriter(job, path, fileSchema);
- } catch (WriteProcessException e) {
- e.printStackTrace();
- throw new InterruptedException("construct TsFileRecordWriter failed");
- }
+ return new TsFileRecordWriter(job, path, fileSchema);
}
}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileRecordWriter.java b/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileRecordWriter.java
index 1fce40c..7e57919 100644
--- a/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileRecordWriter.java
+++ b/spark/src/main/java/org/apache/iotdb/tsfile/io/TsFileRecordWriter.java
@@ -23,31 +23,32 @@ import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.RecordWriter;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
-import org.apache.iotdb.tsfile.timeseries.basis.TsFile;
-import org.apache.iotdb.tsfile.write.exception.WriteProcessException;
+import org.apache.iotdb.tsfile.exception.write.WriteProcessException;
+import org.apache.iotdb.tsfile.write.TsFileWriter;
import org.apache.iotdb.tsfile.write.record.TSRecord;
import org.apache.iotdb.tsfile.write.schema.FileSchema;
public class TsFileRecordWriter extends RecordWriter<NullWritable, TSRecord> {
- private TsFile tsFile = null;
+ private TsFileWriter tsFileWriter = null;
public TsFileRecordWriter(TaskAttemptContext job, Path file, FileSchema fileSchema)
- throws IOException, WriteProcessException {
- HDFSOutputStream hdfsOutputStream = new HDFSOutputStream(file.toString(),
- job.getConfiguration(), false);
- tsFile = new TsFile(hdfsOutputStream, fileSchema);
+ throws IOException {
+ HDFSOutput hdfsOutput = new HDFSOutput(file.toString(),
+ job.getConfiguration(), false); //NOTE overwrite false here
+
+ tsFileWriter = new TsFileWriter(hdfsOutput, fileSchema);
}
@Override
public void close(TaskAttemptContext context) throws IOException {
- tsFile.close();
+ tsFileWriter.close();
}
@Override
public synchronized void write(NullWritable arg0, TSRecord tsRecord) throws IOException {
try {
- tsFile.writeRecord(tsRecord);
+ tsFileWriter.write(tsRecord);
} catch (WriteProcessException e) {
e.printStackTrace();
}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/Executor.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/Executor.java
deleted file mode 100755
index bfcbbae..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/Executor.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import org.apache.iotdb.tsfile.common.utils.ITsRandomAccessFileReader;
-import org.apache.iotdb.tsfile.read.query.QueryConfig;
-import org.apache.iotdb.tsfile.read.query.QueryDataSet;
-import org.apache.iotdb.tsfile.read.query.QueryEngine;
-
-/**
- * This class used to execute Queries on TSFile
- */
-public class Executor {
-
- public static List<QueryDataSet> query(ITsRandomAccessFileReader in,
- List<QueryConfig> queryConfigs, HashMap<String, Long> parameters) {
- QueryEngine queryEngine;
- List<QueryDataSet> dataSets = new ArrayList<>();
- try {
- queryEngine = new QueryEngine(in);
- for (QueryConfig queryConfig : queryConfigs) {
- QueryDataSet queryDataSet = queryEngine.query(queryConfig, parameters);
- dataSets.add(queryDataSet);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- return dataSets;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/QueryProcessor.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/QueryProcessor.java
deleted file mode 100755
index 62dabe8..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/QueryProcessor.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.iotdb.tsfile.common.utils.ITsRandomAccessFileReader;
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.common.SQLConstant;
-import org.apache.iotdb.tsfile.qp.common.SingleQuery;
-import org.apache.iotdb.tsfile.qp.common.TSQueryPlan;
-import org.apache.iotdb.tsfile.qp.exception.QueryOperatorException;
-import org.apache.iotdb.tsfile.qp.exception.QueryProcessorException;
-import org.apache.iotdb.tsfile.qp.optimizer.DNFFilterOptimizer;
-import org.apache.iotdb.tsfile.qp.optimizer.MergeSingleFilterOptimizer;
-import org.apache.iotdb.tsfile.qp.optimizer.PhysicalOptimizer;
-import org.apache.iotdb.tsfile.qp.optimizer.RemoveNotOptimizer;
-
-
-/**
- * This class is used to convert information given by sparkSQL to construct TSFile's query plans.
- * For TSFile's schema differ from SparkSQL's table schema
- * e.g.
- * TSFile's SQL: select s1,s2 from root.car.d1 where s1 = 10
- * SparkSQL's SQL: select s1,s2 from XXX where delta_object = d1
- *
- */
-public class QueryProcessor {
-
- //construct logical query plans first, then convert them to physical ones
- public List<TSQueryPlan> generatePlans(FilterOperator filter, List<String> paths,
- List<String> columnNames,
- ITsRandomAccessFileReader in, Long start, Long end)
- throws QueryProcessorException, IOException {
-
- List<TSQueryPlan> queryPlans = new ArrayList<>();
-
- if (filter != null) {
- RemoveNotOptimizer removeNot = new RemoveNotOptimizer();
- filter = removeNot.optimize(filter);
-
- DNFFilterOptimizer dnf = new DNFFilterOptimizer();
- filter = dnf.optimize(filter);
-
- MergeSingleFilterOptimizer merge = new MergeSingleFilterOptimizer();
- filter = merge.optimize(filter);
-
- List<FilterOperator> filterOperators = splitFilter(filter);
-
- for (FilterOperator filterOperator : filterOperators) {
- SingleQuery singleQuery = constructSelectPlan(filterOperator, columnNames);
- if (singleQuery != null) {
- queryPlans.addAll(
- new PhysicalOptimizer(columnNames).optimize(singleQuery, paths, in, start, end));
- }
- }
- } else {
- queryPlans.addAll(new PhysicalOptimizer(columnNames).optimize(null, paths, in, start, end));
- }
- return queryPlans;
- }
-
- private List<FilterOperator> splitFilter(FilterOperator filterOperator) {
- if (filterOperator.isSingle() || filterOperator.getTokenIntType() != SQLConstant.KW_OR) {
- List<FilterOperator> ret = new ArrayList<>();
- ret.add(filterOperator);
- return ret;
- }
- // a list of conjunctions linked by or
- return filterOperator.childOperators;
- }
-
- private SingleQuery constructSelectPlan(FilterOperator filterOperator, List<String> columnNames)
- throws QueryOperatorException {
- FilterOperator timeFilter = null;
- FilterOperator valueFilter = null;
- List<FilterOperator> columnFilterOperators = new ArrayList<>();
-
- List<FilterOperator> singleFilterList = null;
-
- if (filterOperator.isSingle()) {
- singleFilterList = new ArrayList<>();
- singleFilterList.add(filterOperator);
-
- } else if (filterOperator.getTokenIntType() == SQLConstant.KW_AND) {
- // original query plan has been dealt with merge optimizer, thus all nodes with same path have been
- // merged to one node
- singleFilterList = filterOperator.getChildren();
- }
-
- if (singleFilterList == null) {
- return null;
- }
-
- List<FilterOperator> valueList = new ArrayList<>();
- for (FilterOperator child : singleFilterList) {
- if (!child.isSingle()) {
- valueList.add(child);
- } else {
- String singlePath = child.getSinglePath();
- if (columnNames.contains(singlePath)) {
- if (!columnFilterOperators.contains(child)) {
- columnFilterOperators.add(child);
- } else {
- throw new QueryOperatorException(
- "The same key filter has been specified more than once: " + singlePath);
- }
- } else {
- switch (child.getSinglePath()) {
- case RESERVED_TIME:
- if (timeFilter != null) {
- throw new QueryOperatorException(
- "time filter has been specified more than once");
- }
- timeFilter = child;
- break;
- default:
- valueList.add(child);
- break;
- }
- }
- }
- }
-
- if (valueList.size() == 1) {
- valueFilter = valueList.get(0);
-
- } else if (valueList.size() > 1) {
- valueFilter = new FilterOperator(SQLConstant.KW_AND, false);
- valueFilter.childOperators = valueList;
- }
-
- return new SingleQuery(columnFilterOperators, timeFilter, valueFilter);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/BasicOperator.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/BasicOperator.java
deleted file mode 100755
index c3a893c..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/BasicOperator.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-
-import org.apache.iotdb.tsfile.qp.exception.BasicOperatorException;
-
-/**
- * basic operators include < > >= <= !=.
- *
- */
-
-public class BasicOperator extends FilterOperator {
-
- private String seriesPath;
- private String seriesValue;
-
- public BasicOperator(int tokenIntType, String path, String value) {
- super(tokenIntType);
- this.seriesPath = this.singlePath = path;
- this.seriesValue = value;
- this.isLeaf = true;
- this.isSingle = true;
- }
-
- public String getSeriesPath() {
- return seriesPath;
- }
-
- public String getSeriesValue() {
- return seriesValue;
- }
-
- public void setReversedTokenIntType() throws BasicOperatorException {
- int intType = SQLConstant.reverseWords.get(tokenIntType);
- setTokenIntType(intType);
- }
-
- @Override
- public String getSinglePath() {
- return singlePath;
- }
-
-
- @Override
- public BasicOperator clone() {
- BasicOperator ret;
- ret = new BasicOperator(this.tokenIntType, seriesPath, seriesValue);
- ret.tokenSymbol = tokenSymbol;
- ret.isLeaf = isLeaf;
- ret.isSingle = isSingle;
- return ret;
- }
-
- @Override
- public String toString() {
- return "[" + seriesPath + tokenSymbol + seriesValue + "]";
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/FilterOperator.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/FilterOperator.java
deleted file mode 100755
index 96b4d89..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/FilterOperator.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.iotdb.tsfile.utils.StringContainer;
-
-
-/**
- * This class is for filter operator and implements
- * {@link Operator} .<br>
- * it may consist of more than two child FilterOperator, but if it's not leaf operator, the relation
- * is same among all of its children.(AND or OR). It's identified by tokenType.
- *
- */
-public class FilterOperator extends Operator implements Comparable<FilterOperator> {
-
- public List<FilterOperator> childOperators;
- // leaf filter operator means it doesn't have left and right child filterOperator. Leaf filter
- // should be BasicOperator.
- protected boolean isLeaf = false;
- // All recursive children of this filter belong to one series path when isSingle variable is true
- protected boolean isSingle = false;
- // if isSingle = false, singlePath must be null
- protected String singlePath = null;
-
- public FilterOperator(int tokenType) {
- super(tokenType);
- childOperators = new ArrayList<>();
- }
-
- public FilterOperator(int tokenType, boolean isSingle) {
- this(tokenType);
- this.isSingle = isSingle;
- }
-
- public void setTokenIntType(int intType) {
- super.tokenIntType = intType;
- super.tokenSymbol = SQLConstant.tokenSymbol.get(tokenIntType);
- }
-
- public void addHeadDeltaObjectPath(String deltaObject) {
- for (FilterOperator child : childOperators) {
- child.addHeadDeltaObjectPath(deltaObject);
- }
- if (isSingle) {
- this.singlePath = deltaObject + "." + this.singlePath;
- }
- }
-
- public List<FilterOperator> getChildren() {
- return childOperators;
- }
-
- public List<String> getAllPaths() {
- List<String> paths = new ArrayList<>();
- if (isLeaf) {
- paths.add(singlePath);
- } else {
- for (FilterOperator child : childOperators) {
- paths.addAll(child.getAllPaths());
- }
- }
- return paths;
- }
-
- public void setChildrenList(List<FilterOperator> children) {
- this.childOperators = children;
- }
-
- public void setIsSingle(boolean b) {
- this.isSingle = b;
- }
-
- public String getSinglePath() {
- return singlePath;
- }
-
- public void setSinglePath(String p) {
- this.singlePath = p;
- }
-
- public void addChildOPerator(FilterOperator op) {
- childOperators.add(op);
- }
-
-
- @Override
- public int compareTo(FilterOperator operator) {
- if (singlePath == null && operator.singlePath == null) {
- return 0;
- }
- if (singlePath == null) {
- return 1;
- }
- if (operator.singlePath == null) {
- return -1;
- }
- return operator.singlePath.compareTo(singlePath);
- }
-
-
- public boolean isLeaf() {
- return isLeaf;
- }
-
- public boolean isSingle() {
- return isSingle;
- }
-
- @Override
- public String toString() {
- StringContainer sc = new StringContainer();
- sc.addTail("[", this.tokenSymbol);
- if (isSingle) {
- sc.addTail("[single:", getSinglePath(), "]");
- }
- sc.addTail(" ");
- for (FilterOperator filter : childOperators) {
- sc.addTail(filter.toString());
- }
- sc.addTail("]");
- return sc.toString();
- }
-
- @Override
- public FilterOperator clone() {
- FilterOperator ret = new FilterOperator(this.tokenIntType);
- ret.tokenSymbol = tokenSymbol;
- ret.isLeaf = isLeaf;
- ret.isSingle = isSingle;
- if (singlePath != null) {
- ret.singlePath = singlePath;
- }
- for (FilterOperator filterOperator : this.childOperators) {
- ret.addChildOPerator(filterOperator.clone());
- }
- return ret;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/Operator.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/Operator.java
deleted file mode 100755
index 684e0e5..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/Operator.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-/**
- * This class is a superclass of all operator.
- *
- */
-public abstract class Operator {
-
- int tokenIntType;
- String tokenSymbol;
-
- Operator(int tokenIntType) {
- this.tokenIntType = tokenIntType;
- this.tokenSymbol = SQLConstant.tokenSymbol.get(tokenIntType);
- }
-
- public int getTokenIntType() {
- return tokenIntType;
- }
-
- public String getTokenSymbol() {
- return tokenSymbol;
- }
-
- @Override
- public String toString() {
- return tokenSymbol;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SQLConstant.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SQLConstant.java
deleted file mode 100644
index 76234e4..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SQLConstant.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * this class contains several constants used in SQL.
- *
- */
-public class SQLConstant {
-
- public static final String DELTA_OBJECT_NAME = "delta_object_name";
- public static final String REGEX_PATH_SEPARATOR = "\\.";
- public static final String PATH_SEPARATOR = ".";
- public static final String RESERVED_TIME = "time";
- public static final String RESERVED_FREQ = "freq";
- public static final String RESERVED_DELTA_OBJECT = "delta_object";
- public static final String INT32 = "INT32";
- public static final String INT64 = "INT64";
- public static final String FLOAT = "FLOAT";
- public static final String DOUBLE = "DOUBLE";
- public static final String BYTE_ARRAY = "BYTE_ARRAY";
-
- public static final int KW_AND = 1;
- public static final int KW_OR = 2;
- public static final int KW_NOT = 3;
-
- public static final int EQUAL = 11;
- public static final int NOTEQUAL = 12;
- public static final int LESSTHANOREQUALTO = 13;
- public static final int LESSTHAN = 14;
- public static final int GREATERTHANOREQUALTO = 15;
- public static final int GREATERTHAN = 16;
- public static final int EQUAL_NS = 17;
-
- public static final int TOK_SELECT = 21;
- public static final int TOK_FROM = 22;
- public static final int TOK_WHERE = 23;
- public static final int TOK_INSERT = 24;
- public static final int TOK_DELETE = 25;
- public static final int TOK_UPDATE = 26;
- public static final int TOK_QUERY = 27;
-
- public static final int TOK_AUTHOR_CREATE = 41;
- public static final int TOK_AUTHOR_DROP = 42;
- public static final int TOK_AUTHOR_GRANT = 43;
- public static final int TOK_AUTHOR_REVOKE = 44;
-
- public static final int TOK_DATALOAD = 45;
-
- public static final int TOK_METADATA_CREATE = 51;
- public static final int TOK_METADATA_DELETE = 52;
- public static final int TOK_METADATA_SET_FILE_LEVEL = 53;
- public static final int TOK_PORPERTY_CREATE = 54;
- public static final int TOK_PORPERTY_ADD_LABEL = 55;
- public static final int TOK_PORPERTY_DELETE_LABEL = 56;
- public static final int TOK_PORPERTY_LINK = 57;
- public static final int TOK_PORPERTY_UNLINK = 58;
-
-
- public static Map<Integer, String> tokenSymbol = new HashMap<Integer, String>();
- public static Map<Integer, String> tokenNames = new HashMap<Integer, String>();
- public static Map<Integer, Integer> reverseWords = new HashMap<Integer, Integer>();
-
- static {
- tokenSymbol.put(KW_AND, "&");
- tokenSymbol.put(KW_OR, "|");
- tokenSymbol.put(KW_NOT, "!");
- tokenSymbol.put(EQUAL, "=");
- tokenSymbol.put(NOTEQUAL, "<>");
- tokenSymbol.put(EQUAL_NS, "<=>");
- tokenSymbol.put(LESSTHANOREQUALTO, "<=");
- tokenSymbol.put(LESSTHAN, "<");
- tokenSymbol.put(GREATERTHANOREQUALTO, ">=");
- tokenSymbol.put(GREATERTHAN, ">");
- }
-
- static {
- tokenNames.put(KW_AND, "and");
- tokenNames.put(KW_OR, "or");
- tokenNames.put(KW_NOT, "not");
- tokenNames.put(EQUAL, "equal");
- tokenNames.put(NOTEQUAL, "not_equal");
- tokenNames.put(EQUAL_NS, "equal_ns");
- tokenNames.put(LESSTHANOREQUALTO, "lessthan_or_equalto");
- tokenNames.put(LESSTHAN, "lessthan");
- tokenNames.put(GREATERTHANOREQUALTO, "greaterthan_or_equalto");
- tokenNames.put(GREATERTHAN, "greaterthan");
-
- tokenNames.put(TOK_SELECT, "TOK_SELECT");
- tokenNames.put(TOK_FROM, "TOK_FROM");
- tokenNames.put(TOK_WHERE, "TOK_WHERE");
- tokenNames.put(TOK_INSERT, "TOK_INSERT");
- tokenNames.put(TOK_DELETE, "TOK_DELETE");
- tokenNames.put(TOK_UPDATE, "TOK_UPDATE");
- tokenNames.put(TOK_QUERY, "TOK_QUERY");
-
- tokenNames.put(TOK_AUTHOR_CREATE, "TOK_AUTHOR_CREATE");
- tokenNames.put(TOK_AUTHOR_DROP, "TOK_AUTHOR_DROP");
- tokenNames.put(TOK_AUTHOR_GRANT, "TOK_AUTHOR_GRANT");
- tokenNames.put(TOK_AUTHOR_REVOKE, "TOK_AUTHOR_REVOKE");
- tokenNames.put(TOK_DATALOAD, "TOK_DATALOAD");
-
- tokenNames.put(TOK_METADATA_CREATE, "TOK_METADATA_CREATE");
- tokenNames.put(TOK_METADATA_DELETE, "TOK_METADATA_DELETE");
- tokenNames.put(TOK_METADATA_SET_FILE_LEVEL, "TOK_METADATA_SET_FILE_LEVEL");
- tokenNames.put(TOK_PORPERTY_CREATE, "TOK_PORPERTY_CREATE");
- tokenNames.put(TOK_PORPERTY_ADD_LABEL, "TOK_PORPERTY_ADD_LABEL");
- tokenNames.put(TOK_PORPERTY_DELETE_LABEL, "TOK_PORPERTY_DELETE_LABEL");
- tokenNames.put(TOK_PORPERTY_LINK, "TOK_PORPERTY_LINK");
- tokenNames.put(TOK_PORPERTY_UNLINK, "TOK_PORPERTY_UNLINK");
-
- }
-
- static {
- reverseWords.put(KW_AND, KW_OR);
- reverseWords.put(KW_OR, KW_AND);
- reverseWords.put(EQUAL, NOTEQUAL);
- reverseWords.put(NOTEQUAL, EQUAL);
- reverseWords.put(LESSTHAN, GREATERTHANOREQUALTO);
- reverseWords.put(GREATERTHANOREQUALTO, LESSTHAN);
- reverseWords.put(LESSTHANOREQUALTO, GREATERTHAN);
- reverseWords.put(GREATERTHAN, LESSTHANOREQUALTO);
- }
-
- public static boolean isReservedPath(String pathStr) {
- return pathStr.equals(SQLConstant.RESERVED_TIME)
- || pathStr.equals(SQLConstant.RESERVED_FREQ)
- || pathStr.equals(SQLConstant.RESERVED_DELTA_OBJECT);
-
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SingleQuery.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SingleQuery.java
deleted file mode 100755
index 2b03652..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/SingleQuery.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-
-import java.util.List;
-
-/**
- * This class is constructed with a single getIndex plan. Single getIndex means it could be processed by
- * reading API by one pass directly.<br>
- *
- */
-public class SingleQuery {
-
- private List<FilterOperator> columnFilterOperators;
- private FilterOperator timeFilterOperator;
- private FilterOperator valueFilterOperator;
-
- public SingleQuery(List<FilterOperator> columnFilterOperators,
- FilterOperator timeFilter, FilterOperator valueFilter) {
- super();
- this.columnFilterOperators = columnFilterOperators;
- this.timeFilterOperator = timeFilter;
- this.valueFilterOperator = valueFilter;
- }
-
- public List<FilterOperator> getColumnFilterOperator() {
-
- return columnFilterOperators;
- }
-
- public FilterOperator getTimeFilterOperator() {
- return timeFilterOperator;
- }
-
- public FilterOperator getValueFilterOperator() {
- return valueFilterOperator;
- }
-
- @Override
- public String toString() {
- return "SingleQuery: \n" + columnFilterOperators + "\n" + timeFilterOperator + "\n"
- + valueFilterOperator;
- }
-
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/TSQueryPlan.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/TSQueryPlan.java
deleted file mode 100755
index e412f96..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/common/TSQueryPlan.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.common;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * One tsfile logical query plan that can be performed at one time
- *
- */
-public class TSQueryPlan {
-
- private List<String> paths = new ArrayList<>();
- private FilterOperator timeFilterOperator;
- private FilterOperator valueFilterOperator;
-
- public TSQueryPlan(List<String> paths, FilterOperator timeFilter, FilterOperator valueFilter) {
- this.paths = paths;
- this.timeFilterOperator = timeFilter;
- this.valueFilterOperator = valueFilter;
- }
-
- public List<String> getPaths() {
- return paths;
- }
-
- public FilterOperator getTimeFilterOperator() {
- return timeFilterOperator;
- }
-
- public FilterOperator getValueFilterOperator() {
- return valueFilterOperator;
- }
-
- public String toString() {
- String ret = "";
- ret += paths.toString();
- if (timeFilterOperator != null) {
- ret += timeFilterOperator.toString();
- }
- if (valueFilterOperator != null) {
- ret += valueFilterOperator.toString();
- }
- return ret;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/BasicOperatorException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/BasicOperatorException.java
deleted file mode 100755
index be36f35..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/BasicOperatorException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-
-/**
- * This exception is threw whiling meeting error in BasicOperator
- *
- */
-public class BasicOperatorException extends QueryProcessorException {
-
- private static final long serialVersionUID = -2163809754074237707L;
-
- public BasicOperatorException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/DNFOptimizeException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/DNFOptimizeException.java
deleted file mode 100755
index c27ef55..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/DNFOptimizeException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-
-/**
- * This exception is threw whiling meeting error in
- *
- */
-public class DNFOptimizeException extends LogicalOptimizeException {
-
- private static final long serialVersionUID = 807384397361662482L;
-
- public DNFOptimizeException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/LogicalOptimizeException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/LogicalOptimizeException.java
deleted file mode 100755
index 4606824..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/LogicalOptimizeException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-/**
- * This exception is threw whiling meeting error in logical optimizer process
- *
- */
-public class LogicalOptimizeException extends QueryProcessorException {
-
- private static final long serialVersionUID = -7098092782689670064L;
-
- public LogicalOptimizeException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/MergeFilterException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/MergeFilterException.java
deleted file mode 100644
index 114d5b6..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/MergeFilterException.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-
-public class MergeFilterException extends LogicalOptimizeException {
-
- private static final long serialVersionUID = 8581594261924961899L;
-
- public MergeFilterException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryOperatorException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryOperatorException.java
deleted file mode 100644
index fc9f177..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryOperatorException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-public class QueryOperatorException extends LogicalOptimizeException {
-
- private static final long serialVersionUID = 8581594261924961899L;
-
- public QueryOperatorException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryProcessorException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryProcessorException.java
deleted file mode 100755
index 9aba40f..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/QueryProcessorException.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-/**
- * This exception is threw whiling meeting error in query processor
- *
- */
-public class QueryProcessorException extends Exception {
-
- private static final long serialVersionUID = -8987915921329335088L;
-
- private String errMsg;
-
- QueryProcessorException(String msg) {
- super(msg);
- this.errMsg = msg;
- }
-
- @Override
- public String getMessage() {
- return errMsg;
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/RemoveNotException.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/RemoveNotException.java
deleted file mode 100755
index df4f6e4..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/exception/RemoveNotException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.exception;
-
-
-/**
- * This exception is threw whiling meeting error in
- *
- */
-public class RemoveNotException extends LogicalOptimizeException {
-
- private static final long serialVersionUID = -772591029262375715L;
-
- public RemoveNotException(String msg) {
- super(msg);
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/DNFFilterOptimizer.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/DNFFilterOptimizer.java
deleted file mode 100755
index 6b9b4fe..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/DNFFilterOptimizer.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.optimizer;
-
-import static org.apache.iotdb.tsfile.qp.common.SQLConstant.KW_AND;
-import static org.apache.iotdb.tsfile.qp.common.SQLConstant.KW_OR;
-
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.exception.DNFOptimizeException;
-
-
-public class DNFFilterOptimizer implements IFilterOptimizer {
-
- /**
- * get DNF(disjunctive normal form) for this filter operator tree.
- * Before invoking getDNF function, make sure that operator tree must be binary tree.
- * In other words, each non-leaf node has exactly two children.
- *
- * @param filter filter operator to be optimized
- * @return FilterOperator
- * @throws DNFOptimizeException exception in DNF optimizing
- */
- @Override
- public FilterOperator optimize(FilterOperator filter) throws DNFOptimizeException {
- return getDNF(filter);
- }
-
- private FilterOperator getDNF(FilterOperator filter) throws DNFOptimizeException {
- if (filter.isLeaf()) {
- return filter;
- }
- List<FilterOperator> children = filter.getChildren();
- if (children.size() != 2) {
- throw new DNFOptimizeException("node :" + filter.getTokenSymbol() + " has "
- + children.size() + " children");
-
- }
- FilterOperator left = getDNF(children.get(0));
- FilterOperator right = getDNF(children.get(1));
- List<FilterOperator> newChildrenList = new ArrayList<>();
- switch (filter.getTokenIntType()) {
- case KW_OR:
- addChildOpInOr(left, newChildrenList);
- addChildOpInOr(right, newChildrenList);
- break;
- case KW_AND:
- if (left.getTokenIntType() != KW_OR && right.getTokenIntType() != KW_OR) {
- addChildOpInAnd(left, newChildrenList);
- addChildOpInAnd(right, newChildrenList);
- } else {
- List<FilterOperator> leftAndChildren = getAndChild(left);
- List<FilterOperator> rightAndChildren = getAndChild(right);
- for (FilterOperator laChild : leftAndChildren) {
- for (FilterOperator raChild : rightAndChildren) {
- FilterOperator r = mergeToConjunction(laChild.clone(), raChild.clone());
- newChildrenList.add(r);
- }
- }
- filter.setTokenIntType(KW_OR);
- }
- break;
- default:
- throw new DNFOptimizeException("get DNF failed, this tokenType is:"
- + filter.getTokenIntType());
- }
- filter.setChildrenList(newChildrenList);
- return filter;
- }
-
- /**
- * Merge two conjunction filter operators into one.<br>
- * conjunction operator consists of {@code FilterOperator} and inner operator which token is
- * KW_AND.<br>
- * e.g. (a and b) merge (c) is (a and b and c)
- *
- * @param a
- * @param b
- * @return FilterOperator
- * @throws DNFOptimizeException
- */
- private FilterOperator mergeToConjunction(FilterOperator a, FilterOperator b)
- throws DNFOptimizeException {
- List<FilterOperator> retChildrenList = new ArrayList<>();
- addChildOpInAnd(a, retChildrenList);
- addChildOpInAnd(b, retChildrenList);
- FilterOperator ret = new FilterOperator(KW_AND, false);
- ret.setChildrenList(retChildrenList);
- return ret;
- }
-
- /**
- * Obtain conjunction node according to input filter operator's token type.
- * If token type == KW_OR, return its children. Otherwise, return a list contains input filter operator
- *
- * @param child
- * @return List<FilterOperator>
- */
- private List<FilterOperator> getAndChild(FilterOperator child) {
- switch (child.getTokenIntType()) {
- case KW_OR:
- return child.getChildren();
- default:
- // other token type means leaf node or "and" operator
- List<FilterOperator> ret = new ArrayList<>();
- ret.add(child);
- return ret;
- }
- }
-
- /**
- * @param child
- * @param newChildrenList
- * @throws DNFOptimizeException
- */
- private void addChildOpInAnd(FilterOperator child, List<FilterOperator> newChildrenList)
- throws DNFOptimizeException {
- if (child.isLeaf()) {
- newChildrenList.add(child);
- } else if (child.getTokenIntType() == KW_AND) {
- newChildrenList.addAll(child.getChildren());
- } else {
- throw new DNFOptimizeException(
- "add all children of an OR operator to newChildrenList in AND");
- }
- }
-
- /**
- * @param child
- * @param newChildrenList
- */
- private void addChildOpInOr(FilterOperator child, List<FilterOperator> newChildrenList) {
- if (child.isLeaf() || child.getTokenIntType() == KW_AND) {
- newChildrenList.add(child);
- } else {
- newChildrenList.addAll(child.getChildren());
- }
- }
-
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/IFilterOptimizer.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/IFilterOptimizer.java
deleted file mode 100755
index 44d00fc..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/IFilterOptimizer.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.optimizer;
-
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.exception.DNFOptimizeException;
-import org.apache.iotdb.tsfile.qp.exception.MergeFilterException;
-import org.apache.iotdb.tsfile.qp.exception.RemoveNotException;
-
-/**
- * provide a filter operator, optimize it.
- *
- */
-public interface IFilterOptimizer {
-
- FilterOperator optimize(FilterOperator filter)
- throws RemoveNotException, DNFOptimizeException, MergeFilterException;
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/MergeSingleFilterOptimizer.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/MergeSingleFilterOptimizer.java
deleted file mode 100755
index 1bc6273..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/MergeSingleFilterOptimizer.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.optimizer;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import org.apache.iotdb.tsfile.qp.common.BasicOperator;
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.exception.MergeFilterException;
-
-public class MergeSingleFilterOptimizer implements IFilterOptimizer {
-
- @Override
- public FilterOperator optimize(FilterOperator filter) throws MergeFilterException {
- mergeSamePathFilter(filter);
-
- return filter;
- }
-
- private String mergeSamePathFilter(FilterOperator filter) throws MergeFilterException {
- if (filter.isLeaf()) {
- return filter.getSinglePath();
- }
- List<FilterOperator> children = filter.getChildren();
- if (children.isEmpty()) {
- throw new MergeFilterException("this inner filter has no children!");
- }
- if (children.size() == 1) {
- throw new MergeFilterException("this inner filter has just one child!");
- }
- String childPath = mergeSamePathFilter(children.get(0));
- String tempPath;
- for (int i = 1; i < children.size(); i++) {
- tempPath = mergeSamePathFilter(children.get(i));
- // if one of children differs from others or is not single node(path = null), filter's path
- // is null
- if (tempPath == null || !tempPath.equals(childPath)) {
- childPath = null;
- }
- }
- if (childPath != null) {
- filter.setIsSingle(true);
- filter.setSinglePath(childPath);
- return childPath;
- }
-
- // make same paths close
- Collections.sort(children);
- List<FilterOperator> ret = new ArrayList<>();
-
- List<FilterOperator> tempExtrNode = null;
- int i;
- for (i = 0; i < children.size(); i++) {
- tempPath = children.get(i).getSinglePath();
- // sorted by path, all "null" paths are in the end
- if (tempPath == null) {
- break;
- }
- if (childPath == null) {
- // first child to be added
- childPath = tempPath;
- tempExtrNode = new ArrayList<>();
- tempExtrNode.add(children.get(i));
- } else if (childPath.equals(tempPath)) {
- // successive next single child with same path,merge it with previous children
- tempExtrNode.add(children.get(i));
- } else {
- // not more same, add exist nodes in tempExtrNode into a new node
- // prevent make a node which has only one child.
- if (tempExtrNode.size() == 1) {
- ret.add(tempExtrNode.get(0));
- // use exist Object directly for efficiency
- tempExtrNode.set(0, children.get(i));
- childPath = tempPath;
- } else {
- // add a new inner node
- FilterOperator newFilter = new FilterOperator(filter.getTokenIntType(), true);
- newFilter.setSinglePath(childPath);
- newFilter.setChildrenList(tempExtrNode);
- ret.add(newFilter);
- tempExtrNode = new ArrayList<>();
- tempExtrNode.add(children.get(i));
- childPath = tempPath;
- }
- }
- }
- // the last several children before "not single paths" has not been added to ret list.
- if (childPath != null) {
- if (tempExtrNode.size() == 1) {
- ret.add(tempExtrNode.get(0));
- } else {
- // add a new inner node
- FilterOperator newFil = new FilterOperator(filter.getTokenIntType(), true);
- newFil.setSinglePath(childPath);
- newFil.setChildrenList(tempExtrNode);
- ret.add(newFil);
- }
- }
- // add last null children
- for (; i < children.size(); i++) {
- ret.add(children.get(i));
- }
- if (ret.size() == 1) {
- // all children have same path, which means this filter node is a single node
- filter.setIsSingle(true);
- filter.setSinglePath(childPath);
- filter.setChildrenList(ret.get(0).getChildren());
- return childPath;
- } else {
- filter.setIsSingle(false);
- filter.setChildrenList(ret);
- return null;
- }
- }
-
- private boolean allIsBasic(List<FilterOperator> children) {
- for (FilterOperator child : children) {
- if (!(child instanceof BasicOperator)) {
- return false;
- }
- }
- return true;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/PhysicalOptimizer.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/PhysicalOptimizer.java
deleted file mode 100644
index 57753ab..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/PhysicalOptimizer.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.optimizer;
-
-import java.io.IOException;
-import org.apache.iotdb.tsfile.common.utils.ITsRandomAccessFileReader;
-import org.apache.iotdb.tsfile.common.utils.Pair;
-import org.apache.iotdb.tsfile.qp.common.BasicOperator;
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.common.SQLConstant;
-import org.apache.iotdb.tsfile.qp.common.SingleQuery;
-import org.apache.iotdb.tsfile.qp.common.TSQueryPlan;
-import org.apache.iotdb.tsfile.read.management.SeriesSchema;
-import org.apache.iotdb.tsfile.read.query.QueryEngine;
-
-public class PhysicalOptimizer {
-
- //determine whether to query all delta_objects from TSFile. true means do query.
- private boolean flag;
- private List<String> validDeltaObjects = new ArrayList<>();
- private List<String> columnNames;
-
- public PhysicalOptimizer(List<String> columnNames) {
- this.columnNames = columnNames;
- }
-
- public List<TSQueryPlan> optimize(SingleQuery singleQuery, List<String> paths,
- ITsRandomAccessFileReader in, Long start, Long end) throws IOException {
- QueryEngine queryEngine = new QueryEngine(in);
- List<String> actualDeltaObjects = queryEngine.getAllDeltaObjectUIDByPartition(start, end);
- List<SeriesSchema> actualSeries = queryEngine.getAllSeriesSchema();
-
- List<String> selectedSeries = new ArrayList<>();
- for (String path : paths) {
- if (!columnNames.contains(path) && !path.equals(SQLConstant.RESERVED_TIME)) {
- selectedSeries.add(path);
- }
- }
- FilterOperator timeFilter = null;
- FilterOperator valueFilter = null;
-
- if (singleQuery != null) {
- timeFilter = singleQuery.getTimeFilterOperator();
- valueFilter = singleQuery.getValueFilterOperator();
- if (valueFilter != null) {
- List<String> filterPaths = valueFilter.getAllPaths();
- List<String> actualPaths = new ArrayList<>();
- for (SeriesSchema series : actualSeries) {
- actualPaths.add(series.name);
- }
- //if filter paths doesn't in tsfile, don't query
- if (!actualPaths.containsAll(filterPaths)) {
- return new ArrayList<>();
- }
- }
-
- flag = true;
- Map<String, Set<String>> selectColumns = mergeColumns(singleQuery.getColumnFilterOperator());
- if (!flag) {
- //e.g. where column1 = 'd1' and column2 = 'd2', should not query
- return new ArrayList<>();
- }
-
- //if select deltaObject, then match with measurement
- if (!selectColumns.isEmpty()) {
- combination(actualDeltaObjects, selectColumns, selectColumns.keySet().toArray(), 0,
- new String[selectColumns.size()]);
- } else {
- validDeltaObjects.addAll(queryEngine.getAllDeltaObjectUIDByPartition(start, end));
- }
- } else {
- validDeltaObjects.addAll(queryEngine.getAllDeltaObjectUIDByPartition(start, end));
- }
-
- List<SeriesSchema> fileSeries = queryEngine.getAllSeriesSchema();
- Set<String> seriesSet = new HashSet<>();
- for (SeriesSchema series : fileSeries) {
- seriesSet.add(series.name);
- }
-
- //query all measurements from TSFile
- if (selectedSeries.size() == 0) {
- for (SeriesSchema series : actualSeries) {
- selectedSeries.add(series.name);
- }
- } else {
- //remove paths that doesn't exist in file
- selectedSeries.removeIf(path -> !seriesSet.contains(path));
- }
-
- List<TSQueryPlan> tsFileQueries = new ArrayList<>();
- for (String deltaObject : validDeltaObjects) {
- List<String> newPaths = new ArrayList<>();
- for (String path : selectedSeries) {
- String newPath = deltaObject + SQLConstant.PATH_SEPARATOR + path;
- newPaths.add(newPath);
- }
- if (valueFilter == null) {
- tsFileQueries.add(new TSQueryPlan(newPaths, timeFilter, null));
- } else {
- FilterOperator newValueFilter = valueFilter.clone();
- newValueFilter.addHeadDeltaObjectPath(deltaObject);
- tsFileQueries.add(new TSQueryPlan(newPaths, timeFilter, newValueFilter));
- }
- }
- return tsFileQueries;
- }
-
- /**
- * calculate combinations of selected columns and add valid deltaObjects to validDeltaObjects
- *
- * @param actualDeltaObjects deltaObjects from file
- * @param columnValues e.g. (device:{d1,d2}) (board:{c1,c2}) or (delta_object:{d1,d2})
- * @param columns e.g. device, board
- * @param beginIndex current recursion list index
- * @param values combination of column values
- */
- private void combination(List<String> actualDeltaObjects, Map<String, Set<String>> columnValues,
- Object[] columns, int beginIndex, String[] values) {
- //use delta_object column
- if (columnValues.containsKey(SQLConstant.RESERVED_DELTA_OBJECT)) {
- Set<String> delta_objects = columnValues.get(SQLConstant.RESERVED_DELTA_OBJECT);
- for (String delta_object : delta_objects) {
- if (actualDeltaObjects.contains(delta_object)) {
- validDeltaObjects.add(delta_object);
- }
- }
- return;
- }
-
- if (beginIndex == columns.length) {
- for (String deltaObject : actualDeltaObjects) {
- boolean valid = true;
- //if deltaObject is root.column1_value.column2_value then
- //actualValues is [root, column1_value, column2_value]
- String[] actualValues = deltaObject.split(SQLConstant.REGEX_PATH_SEPARATOR);
- for (int i = 0; i < columns.length; i++) {
- int columnIndex = columnNames.indexOf(columns[i].toString());
- if (!actualValues[columnIndex].equals(values[i])) {
- valid = false;
- }
- }
- if (valid) {
- validDeltaObjects.add(deltaObject);
- }
- }
- return;
- }
-
- for (String c : columnValues.get(columns[beginIndex].toString())) {
- values[beginIndex] = c;
- combination(actualDeltaObjects, columnValues, columns, beginIndex + 1, values);
- }
- }
-
- private Map<String, Set<String>> mergeColumns(List<FilterOperator> columnFilterOperators) {
- Map<String, Set<String>> column_values_map = new HashMap<>();
- for (FilterOperator filterOperator : columnFilterOperators) {
- Pair<String, Set<String>> column_values = mergeColumn(filterOperator);
- if (column_values != null && !column_values.right.isEmpty()) {
- column_values_map.put(column_values.left, column_values.right);
- }
- }
- return column_values_map;
- }
-
- /**
- * merge one column filterOperator
- * @param columnFilterOperator column filter
- * @return selected values of the column filter
- */
- private Pair<String, Set<String>> mergeColumn(FilterOperator columnFilterOperator) {
- if (columnFilterOperator == null) {
- return null;
- }
- if (columnFilterOperator.isLeaf()) {
- Set<String> ret = new HashSet<>();
- ret.add(((BasicOperator) columnFilterOperator).getSeriesValue());
- return new Pair<>(columnFilterOperator.getSinglePath(), ret);
- }
- List<FilterOperator> children = columnFilterOperator.getChildren();
- if (children == null || children.isEmpty()) {
- return new Pair<>(null, new HashSet<>());
- }
- Pair<String, Set<String>> ret = mergeColumn(children.get(0));
- if (ret == null) {
- return null;
- }
- for (int i = 1; i < children.size(); i++) {
- Pair<String, Set<String>> temp = mergeColumn(children.get(i));
- if (temp == null) {
- return null;
- }
- switch (columnFilterOperator.getTokenIntType()) {
- case KW_AND:
- ret.right.retainAll(temp.right);
- //example: "where device = d1 and device = d2" should not query data
- if (ret.right.isEmpty()) {
- flag = false;
- }
- break;
- case KW_OR:
- ret.right.addAll(temp.right);
- break;
- default:
- throw new UnsupportedOperationException(
- "given error token type:" + columnFilterOperator.getTokenIntType());
- }
- }
- return ret;
- }
-}
diff --git a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/RemoveNotOptimizer.java b/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/RemoveNotOptimizer.java
deleted file mode 100755
index 33396ea..0000000
--- a/spark/src/main/java/org/apache/iotdb/tsfile/qp/optimizer/RemoveNotOptimizer.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/**
- * 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.iotdb.tsfile.qp.optimizer;
-
-
-import static org.apache.iotdb.tsfile.qp.common.SQLConstant.KW_AND;
-import static org.apache.iotdb.tsfile.qp.common.SQLConstant.KW_NOT;
-import static org.apache.iotdb.tsfile.qp.common.SQLConstant.KW_OR;
-
-import java.util.List;
-import org.apache.iotdb.tsfile.qp.common.BasicOperator;
-import org.apache.iotdb.tsfile.qp.common.FilterOperator;
-import org.apache.iotdb.tsfile.qp.common.SQLConstant;
-import org.apache.iotdb.tsfile.qp.exception.BasicOperatorException;
-import org.apache.iotdb.tsfile.qp.exception.RemoveNotException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class RemoveNotOptimizer implements IFilterOptimizer {
-
- private static final Logger LOG = LoggerFactory.getLogger(RemoveNotOptimizer.class);
-
- /**
- * get DNF(disjunctive normal form) for this filter operator tree. Before getDNF, this op tree
- * must be binary, in another word, each non-leaf node has exactly two children.
- *
- * @param filter filter operator to be optimized
- * @return optimized filter operator
- * @throws RemoveNotException excepiton in remove not optimizing
- */
- @Override
- public FilterOperator optimize(FilterOperator filter) throws RemoveNotException {
- return removeNot(filter);
- }
-
- private FilterOperator removeNot(FilterOperator filter) throws RemoveNotException {
- if (filter.isLeaf()) {
- return filter;
- }
- int tokenInt = filter.getTokenIntType();
- switch (tokenInt) {
- case KW_AND:
- case KW_OR:
- // replace children in-place for efficiency
- List<FilterOperator> children = filter.getChildren();
- children.set(0, removeNot(children.get(0)));
- children.set(1, removeNot(children.get(1)));
- return filter;
- case KW_NOT:
- try {
- return reverseFilter(filter.getChildren().get(0));
- } catch (BasicOperatorException e) {
- LOG.error("reverse Filter failed.");
- }
- default:
- throw new RemoveNotException("Unknown token in removeNot: " + tokenInt + ","
- + SQLConstant.tokenNames.get(tokenInt));
- }
- }
-
-
- private FilterOperator reverseFilter(FilterOperator filter)
- throws RemoveNotException, BasicOperatorException {
- int tokenInt = filter.getTokenIntType();
- if (filter.isLeaf()) {
- try {
- ((BasicOperator) filter).setReversedTokenIntType();
- } catch (BasicOperatorException e) {
- throw new RemoveNotException(
- "convert BasicFuntion to reserved meet failed: previous token:" + tokenInt
- + "tokenSymbol:" + SQLConstant.tokenNames.get(tokenInt));
- }
- return filter;
- }
- switch (tokenInt) {
- case KW_AND:
- case KW_OR:
- List<FilterOperator> children = filter.getChildren();
- children.set(0, reverseFilter(children.get(0)));
- children.set(1, reverseFilter(children.get(1)));
- filter.setTokenIntType(SQLConstant.reverseWords.get(tokenInt));
- return filter;
- case KW_NOT:
- return removeNot(filter.getChildren().get(0));
- default:
- throw new RemoveNotException("Unknown token in reverseFilter: " + tokenInt + ","
- + SQLConstant.tokenNames.get(tokenInt));
- }
- }
-
-}
diff --git a/spark/src/main/scala/org/apache/iotdb/tsfile/Converter.scala b/spark/src/main/scala/org/apache/iotdb/tsfile/Converter.scala
index 5307e73..38b9999 100755
--- a/spark/src/main/scala/org/apache/iotdb/tsfile/Converter.scala
+++ b/spark/src/main/scala/org/apache/iotdb/tsfile/Converter.scala
@@ -1,88 +1,189 @@
/**
- * 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.
- */
-
+ * 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.iotdb.tsfile
import java.util
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.FileStatus
+import org.apache.iotdb.tsfile.common.conf.TSFileDescriptor
+import org.apache.iotdb.tsfile.common.constant.QueryConstant
+import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData
+import org.apache.iotdb.tsfile.file.metadata.enums.{TSDataType, TSEncoding}
+import org.apache.iotdb.tsfile.io.HDFSInput
+import org.apache.iotdb.tsfile.read.TsFileSequenceReader
+import org.apache.iotdb.tsfile.read.common.{Field, Path}
+import org.apache.iotdb.tsfile.read.expression.impl.{BinaryExpression, GlobalTimeExpression, SingleSeriesExpression}
+import org.apache.iotdb.tsfile.read.expression.{IExpression, QueryExpression}
+import org.apache.iotdb.tsfile.read.filter.{TimeFilter, ValueFilter}
+import org.apache.iotdb.tsfile.utils.Binary
+import org.apache.iotdb.tsfile.write.record.TSRecord
+import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint
+import org.apache.iotdb.tsfile.write.schema.{FileSchema, MeasurementSchema, SchemaBuilder}
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+
+import scala.collection.JavaConversions._
+import scala.collection.mutable
+import scala.collection.mutable.ListBuffer
+
+/**
+ * A series has a name and a type.
+ *
+ * @param nameVar name
+ * @param typeVar type
+ */
+class Series(nameVar: String, typeVar: TSDataType) {
+ var seriesName: String = nameVar
+ var seriesType: TSDataType = typeVar
+
+ def getName = seriesName
+ def getType = seriesType
+
+ override def toString = s"[" + seriesName + "," + seriesType + "]"
+}
+
/**
- * This object contains methods that are used to convert schema and data between sparkSQL and TSFile.
+ * This object contains methods that are used to convert schema and data between SparkSQL and TSFile.
*
*/
object Converter {
/**
- * Get union series in all tsfiles
+ * Get series from the given tsFileMetaData.
+ *
+ * @param tsFileMetaData TsFileMetaData
+ * @return union series
+ */
+ def getSeries(tsFileMetaData: TsFileMetaData): util.ArrayList[Series] = {
+ val series = new util.ArrayList[Series]()
+
+ val devices = tsFileMetaData.getDeviceMap.keySet()
+ val measurements = tsFileMetaData.getMeasurementSchema
+
+ devices.foreach(d => {
+ measurements.foreach(m => {
+ val fullPath = d + "." + m._1
+ series.add(new Series(fullPath, m._2.getType)
+ )
+ })
+ })
+
+ series
+ }
+
+ /**
+ * Get union series in all tsfiles.
* e.g. (tsfile1:s1,s2) & (tsfile2:s2,s3) = s1,s2,s3
*
* @param files tsfiles
* @param conf hadoop configuration
* @return union series
*/
- def getUnionSeries(files: Seq[FileStatus], conf: Configuration): util.ArrayList[SeriesSchema] = {
- val unionSeries = new util.ArrayList[SeriesSchema]()
+ def getUnionSeries(files: Seq[FileStatus], conf: Configuration): util.ArrayList[Series] = {
+ val unionSeries = new util.ArrayList[Series]()
var seriesSet: mutable.Set[String] = mutable.Set()
files.foreach(f => {
- val in = new HDFSInputStream(f.getPath, conf)
- val queryEngine = new QueryEngine(in)
- val series = queryEngine.getAllSeriesSchema
- series.foreach(s => {
- if (!seriesSet.contains(s.name)) {
- seriesSet += s.name
- unionSeries.add(s)
- }
+ val in = new HDFSInput(f.getPath, conf)
+ val reader = new TsFileSequenceReader(in)
+ val tsFileMetaData = reader.readFileMetadata
+ val devices = tsFileMetaData.getDeviceMap.keySet()
+ val measurements = tsFileMetaData.getMeasurementSchema
+
+ devices.foreach(d => {
+ measurements.foreach(m => {
+ val fullPath = d + "." + m._1
+ if (!seriesSet.contains(fullPath)) {
+ seriesSet += fullPath
+ unionSeries.add(new Series(fullPath, m._2.getType)
+ )
+ }
+ })
})
+ in.close()
})
unionSeries
}
/**
- * Convert TSFile columns to sparkSQL schema.
+ * Convert TSFile data to SparkSQL data.
*
- * @param tsfileSchema all time series information in TSFile
- * @param columns e.g. {device:1, board:2} or {delta_object:0}
- * @return sparkSQL table schema
+ * @param field one data point in TsFile
+ * @return SparkSQL data
*/
- def toSqlSchema(tsfileSchema: util.ArrayList[SeriesSchema], columns: ArrayBuffer[String]): Option[StructType] = {
+ def toSqlValue(field: Field): Any = {
+ if (field == null)
+ return null
+ if (field.isNull)
+ null
+ else field.getDataType match {
+ case TSDataType.BOOLEAN => field.getBoolV
+ case TSDataType.INT32 => field.getIntV
+ case TSDataType.INT64 => field.getLongV
+ case TSDataType.FLOAT => field.getFloatV
+ case TSDataType.DOUBLE => field.getDoubleV
+ case TSDataType.TEXT => field.getStringValue
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ }
+
+ /**
+ * Construct fields with the TSFile data type converted to the SparkSQL data type.
+ *
+ * @param tsfileSchema tsfileSchema
+ * @param addTimeField true to add a time field; false to not
+ * @return the converted list of fields
+ */
+ def toSqlField(tsfileSchema: util.ArrayList[Series], addTimeField: Boolean): ListBuffer[StructField] = {
val fields = new ListBuffer[StructField]()
- fields += StructField(SQLConstant.RESERVED_TIME, LongType, nullable = false)
- columns.filter(f => !f.equals("root")) foreach (f => {
- fields += StructField(f, StringType, nullable = false)
- })
+ if (addTimeField) {
+ fields += StructField(QueryConstant.RESERVED_TIME, LongType, nullable = false)
+ }
- tsfileSchema.foreach((series: SeriesSchema) => {
- fields += StructField(series.name, series.dataType match {
+ tsfileSchema.foreach((series: Series) => {
+ fields += StructField(series.getName, series.getType match {
case TSDataType.BOOLEAN => BooleanType
case TSDataType.INT32 => IntegerType
case TSDataType.INT64 => LongType
case TSDataType.FLOAT => FloatType
case TSDataType.DOUBLE => DoubleType
- case TSDataType.ENUMS => StringType
case TSDataType.TEXT => StringType
- case TSDataType.FIXED_LEN_BYTE_ARRAY => BinaryType
case other => throw new UnsupportedOperationException(s"Unsupported type $other")
}, nullable = true)
})
+ fields
+ }
+
+ /**
+ * Convert TSFile columns to SparkSQL schema.
+ *
+ * @param tsfileSchema all time series information in TSFile
+ * @return SparkSQL table schema with the time field added
+ */
+ def toSqlSchema(tsfileSchema: util.ArrayList[Series]): Option[StructType] = {
+ val fields = toSqlField(tsfileSchema, true) // true to add the time field
+
SchemaType(StructType(fields.toList), nullable = false).dataType match {
case t: StructType => Some(t)
case _ => throw new RuntimeException(
@@ -93,160 +194,125 @@ object Converter {
}
/**
- * given a spark sql struct type, generate TsFile schema
+ * Prepare queriedSchema from requiredSchema.
*
- * @param structType given sql schema
- * @return TsFile schema
+ * @param requiredSchema requiredSchema
+ * @param tsFileMetaData tsFileMetaData
+ * @return
*/
- def toTsFileSchema(columnNames: ArrayBuffer[String], structType: StructType, options: Map[String, String]): FileSchema = {
- val schemaBuilder = new SchemaBuilder()
- structType.fields.filter(f => {
- !SQLConstant.isReservedPath(f.name) && !columnNames.contains(f.name)
- }).foreach(f => {
- val seriesSchema = getSeriesSchema(f, options)
- schemaBuilder.addSeries(seriesSchema)
- })
- schemaBuilder.build()
+ def prepSchema(requiredSchema: StructType, tsFileMetaData: TsFileMetaData): StructType = {
+ var queriedSchema: StructType = new StructType()
+
+ if (requiredSchema.isEmpty
+ || (requiredSchema.size == 1 && requiredSchema.iterator.next().name == QueryConstant.RESERVED_TIME)) {
+ // for example, (i) select count(*) from table; (ii) select time from table
+
+ val fileSchema = Converter.getSeries(tsFileMetaData)
+ queriedSchema = StructType(toSqlField(fileSchema, false).toList)
+
+ } else { // Remove nonexistent schema according to the current file's metadata.
+ // This may happen when queried TsFiles in the same folder do not have the same schema.
+
+ val devices = tsFileMetaData.getDeviceMap.keySet()
+ val measurementIds = tsFileMetaData.getMeasurementSchema.keySet()
+ requiredSchema.foreach(f => {
+ if (!QueryConstant.RESERVED_TIME.equals(f.name)) {
+ val path = new org.apache.iotdb.tsfile.read.common.Path(f.name)
+ if (devices.contains(path.getDevice) && measurementIds.contains(path.getMeasurement)) {
+ queriedSchema = queriedSchema.add(f)
+ }
+ }
+ })
+
+ }
+
+ queriedSchema
}
+
/**
- * construct series schema from name and data type
+ * Return the TsFile data type of given SparkSQL data type.
*
- * @param field series name
- * @param options series data type
- * @return series schema
+ * @param dataType SparkSQL data type
+ * @return TsFile data type
*/
- def getSeriesSchema(field: StructField, options: Map[String, String]): MeasurementDescriptor = {
- val conf = TSFileDescriptor.getInstance.getConfig
- val dataType = getTsDataType(field.dataType)
- val encodingStr = dataType match {
- case TSDataType.INT32 => options.getOrElse(SQLConstant.INT32, TSEncoding.RLE.toString)
- case TSDataType.INT64 => options.getOrElse(SQLConstant.INT64, TSEncoding.RLE.toString)
- case TSDataType.FLOAT => options.getOrElse(SQLConstant.FLOAT, TSEncoding.RLE.toString)
- case TSDataType.DOUBLE => options.getOrElse(SQLConstant.DOUBLE, TSEncoding.RLE.toString)
- case TSDataType.TEXT => options.getOrElse(SQLConstant.BYTE_ARRAY, TSEncoding.PLAIN.toString)
+ def getTsDataType(dataType: DataType): TSDataType = {
+ dataType match {
+ case IntegerType => TSDataType.INT32
+ case LongType => TSDataType.INT64
+ case BooleanType => TSDataType.BOOLEAN
+ case FloatType => TSDataType.FLOAT
+ case DoubleType => TSDataType.DOUBLE
+ case StringType => TSDataType.TEXT
case other => throw new UnsupportedOperationException(s"Unsupported type $other")
}
- val encoding = TSEncoding.valueOf(encodingStr)
- new MeasurementDescriptor(field.name, dataType, encoding, null)
}
/**
- * Use information given by sparkSQL to construct TSFile QueryConfigs for querying data.
+ * Construct MeasurementSchema from the given field.
*
- * @param in file input stream
- * @param requiredSchema The schema of the data that should be output for each row.
- * @param filters A set of filters than can optionally be used to reduce the number of rows output
- * @param columnNames e.g. {device:1, board:2}
- * @param start the start offset in file partition
- * @param end the end offset in file partition
- * @return TSFile physical query plans
+ * @param field field
+ * @param options encoding options
+ * @return MeasurementSchema
*/
- def toQueryConfigs(
- in: ITsRandomAccessFileReader,
- requiredSchema: StructType,
- filters: Seq[Filter],
- columnNames: ArrayBuffer[String],
- start: java.lang.Long,
- end: java.lang.Long): Array[QueryConfig] = {
-
- val queryConfigs = new ArrayBuffer[QueryConfig]()
-
- val paths = new ListBuffer[String]()
- requiredSchema.foreach(f => {
- paths.add(f.name)
- })
-
- //remove invalid filters
- val validFilters = new ListBuffer[Filter]()
- filters.foreach { f => {
- if (isValidFilter(f))
- validFilters.add(f)
- }
- }
-
- if (validFilters.isEmpty) {
-
- //generatePlans operatorTree to TSQueryPlan list
- val queryProcessor = new QueryProcessor()
- val queryPlans = queryProcessor.generatePlans(null, paths, columnNames, in, start, end).toArray
-
- //construct TSQueryPlan list to QueryConfig list
- queryPlans.foreach(f => {
- queryConfigs.append(queryToConfig(f.asInstanceOf[TSQueryPlan]))
- })
- } else {
- //construct filters to a binary tree
- var filterTree = validFilters.get(0)
- for (i <- 1 until validFilters.length) {
- filterTree = And(filterTree, validFilters.get(i))
- }
-
- //convert filterTree to FilterOperator
- val operator = transformFilter(filterTree)
-
- //generatePlans operatorTree to TSQueryPlan list
- val queryProcessor = new QueryProcessor()
- val queryPlans = queryProcessor.generatePlans(operator, paths, columnNames, in, start, end).toArray
-
- //construct TSQueryPlan list to QueryConfig list
- queryPlans.foreach(f => {
- queryConfigs.append(queryToConfig(f.asInstanceOf[TSQueryPlan]))
- })
+ def getSeriesSchema(field: StructField, options: Map[String, String]): MeasurementSchema = {
+ val conf = TSFileDescriptor.getInstance.getConfig
+ val dataType = getTsDataType(field.dataType)
+ val encodingStr = dataType match {
+ case TSDataType.INT32 => options.getOrElse(QueryConstant.INT32, TSEncoding.RLE.toString)
+ case TSDataType.INT64 => options.getOrElse(QueryConstant.INT64, TSEncoding.RLE.toString)
+ case TSDataType.FLOAT => options.getOrElse(QueryConstant.FLOAT, TSEncoding.RLE.toString)
+ case TSDataType.DOUBLE => options.getOrElse(QueryConstant.DOUBLE, TSEncoding.RLE.toString)
+ case TSDataType.TEXT => options.getOrElse(QueryConstant.BYTE_ARRAY, TSEncoding.PLAIN.toString)
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
}
- queryConfigs.toArray
+ val encoding = TSEncoding.valueOf(encodingStr)
+ val fullPath = new Path(field.name)
+ val measurement = fullPath.getMeasurement
+ new MeasurementSchema(measurement, dataType, encoding)
}
/**
- * Convert TSFile data to sparkSQL data.
+ * Given a SparkSQL struct type, generate the TsFile schema.
+ * Note: Measurements of the same name should have the same schema.
*
- * @param field one data point in TsFile
- * @return sparkSQL data
+ * @param structType given sql schema
+ * @return TsFile schema
*/
- def toSqlValue(field: Field): Any = {
- if (field == null)
- return null
- if (field.isNull)
- null
- else field.dataType match {
- case TSDataType.BOOLEAN => field.getBoolV
- case TSDataType.INT32 => field.getIntV
- case TSDataType.INT64 => field.getLongV
- case TSDataType.FLOAT => field.getFloatV
- case TSDataType.DOUBLE => field.getDoubleV
- case TSDataType.FIXED_LEN_BYTE_ARRAY => field.getStringValue
- case TSDataType.TEXT => field.getStringValue
- case TSDataType.ENUMS => field.getStringValue
- case other => throw new UnsupportedOperationException(s"Unsupported type $other")
- }
+ def toTsFileSchema(structType: StructType, options: Map[String, String]): FileSchema = {
+ val schemaBuilder = new SchemaBuilder()
+ structType.fields.filter(f => {
+ !QueryConstant.RESERVED_TIME.equals(f.name)
+ }).foreach(f => {
+ val seriesSchema = getSeriesSchema(f, options)
+ schemaBuilder.addSeries(seriesSchema)
+ })
+ schemaBuilder.build()
}
/**
- * convert row to TSRecord
+ * Convert a row in the spark table to a list of TSRecord.
*
- * @param columnNames delta_object column names
- * @param row given spark sql row
+ * @param row given spark sql row
* @return TSRecord
*/
- def toTsRecord(columnNames: ArrayBuffer[String], row: Row): TSRecord = {
+ def toTsRecord(row: Row): List[TSRecord] = {
val schema = row.schema
- val time = row.getAs[Long](SQLConstant.RESERVED_TIME)
- val delta_object = {
- if (columnNames.contains(SQLConstant.RESERVED_DELTA_OBJECT)) {
- row.getAs[String](SQLConstant.RESERVED_DELTA_OBJECT)
- } else {
- var delta_str = "root"
- columnNames.filter(f => !f.equals("root")) foreach (f => {
- delta_str += SQLConstant.PATH_SEPARATOR + row.getAs[String](f)
- })
- delta_str
- }
- }
- val tsRecord = new TSRecord(time, delta_object)
+ val time = row.getAs[Long](QueryConstant.RESERVED_TIME)
+ val deviceToRecord = scala.collection.mutable.Map[String, TSRecord]()
+
schema.fields.filter(f => {
- !SQLConstant.isReservedPath(f.name) && !columnNames.contains(f.name)
+ !QueryConstant.RESERVED_TIME.equals(f.name)
}).foreach(f => {
val name = f.name
+ val fullPath = new Path(name)
+ val device = fullPath.getDevice
+ val measurement = fullPath.getMeasurement
+ if (!deviceToRecord.contains(device)) {
+ deviceToRecord.put(device, new TSRecord(time, device))
+ }
+ val tsRecord: TSRecord = deviceToRecord.getOrElse(device, new TSRecord(time, device))
+
val dataType = getTsDataType(f.dataType)
val index = row.fieldIndex(name)
if (!row.isNullAt(index)) {
@@ -258,28 +324,54 @@ object Converter {
case StringType => row.getAs[String](name)
case other => throw new UnsupportedOperationException(s"Unsupported type $other")
}
- val dataPoint = DataPoint.getDataPoint(dataType, name, value.toString)
+ val dataPoint = DataPoint.getDataPoint(dataType, measurement, value.toString)
tsRecord.addTuple(dataPoint)
}
})
- tsRecord
+ deviceToRecord.values.toList
}
+
/**
- * return the TsFile data type of given spark sql data type
+ * Construct queryExpression based on queriedSchema and filters.
*
- * @param dataType spark sql data type
- * @return TsFile data type
+ * @param schema selected columns
+ * @param filters filters
+ * @return query expression
*/
- def getTsDataType(dataType: DataType): TSDataType = {
- dataType match {
- case IntegerType => TSDataType.INT32
- case LongType => TSDataType.INT64
- case BooleanType => TSDataType.BOOLEAN
- case FloatType => TSDataType.FLOAT
- case DoubleType => TSDataType.DOUBLE
- case StringType => TSDataType.TEXT
- case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ def toQueryExpression(schema: StructType, filters: Seq[Filter]): QueryExpression = {
+ //get paths from schema
+ val paths = new util.ArrayList[org.apache.iotdb.tsfile.read.common.Path]
+ schema.foreach(f => {
+ if (!QueryConstant.RESERVED_TIME.equals(f.name)) { // the time field is excluded
+ paths.add(new org.apache.iotdb.tsfile.read.common.Path(f.name))
+ }
+ })
+
+ //remove invalid filters
+ val validFilters = new ListBuffer[Filter]()
+ filters.foreach { f => {
+ if (isValidFilter(f))
+ validFilters.add(f)
+ }
+ }
+ if (validFilters.isEmpty) {
+ val queryExpression = QueryExpression.create(paths, null)
+ queryExpression
+ } else {
+ //construct filters to a binary tree
+ var filterTree = validFilters.get(0)
+ for (i <- 1 until validFilters.length) {
+ filterTree = And(filterTree, validFilters.get(i))
+ }
+
+ //convert filterTree to FilterOperator
+ val finalFilter = transformFilter(schema, filterTree)
+
+ // create query expression
+ val queryExpression = QueryExpression.create(paths, finalFilter)
+
+ queryExpression
}
}
@@ -298,163 +390,198 @@ object Converter {
}
/**
- * Used in toQueryConfigs() to convert one query plan to one QueryConfig.
- *
- * @param queryPlan TsFile logical query plan
- * @return TsFile physical query plan
- */
- private def queryToConfig(queryPlan: TSQueryPlan): QueryConfig = {
- val selectedColumns = queryPlan.getPaths.toArray
- val timeFilter = queryPlan.getTimeFilterOperator
- val valueFilter = queryPlan.getValueFilterOperator
-
- var select = ""
- var colNum = 0
- selectedColumns.foreach(f => {
- if (colNum == 0) {
- select += f.asInstanceOf[String]
- }
- else {
- select += "|" + f.asInstanceOf[String]
- }
- colNum += 1
- })
-
- var single = false
- if (colNum == 1 && valueFilter != null) {
- if (select.equals(valueFilter.getSinglePath)) {
- single = true
- }
- }
- val timeFilterStr = timeFilterToString(timeFilter)
- val valueFilterStr = valueFilterToString(valueFilter, single)
- new QueryConfig(select, timeFilterStr, "null", valueFilterStr)
- }
-
-
- /**
- * Convert a time filter to QueryConfig's timeFilter parameter.
- *
- * @param operator time filter
- * @return QueryConfig's timeFilter parameter
- */
- private def timeFilterToString(operator: FilterOperator): String = {
- if (operator == null)
- return "null"
-
- "0," + timeFilterToPartString(operator)
- }
-
-
- /**
- * Used in timeFilterToString to construct specified string format.
+ * Transform SparkSQL's filter binary tree to TsFile's filter expression.
*
- * @param operator time filter
- * @return QueryConfig's partial timeFilter parameter
+ * @param schema to get relative columns' dataType information
+ * @param node filter tree's node
+ * @return TSFile filter expression
*/
- private def timeFilterToPartString(operator: FilterOperator): String = {
- val token = operator.getTokenIntType
- token match {
- case SQLConstant.KW_AND =>
- "(" + timeFilterToPartString(operator.getChildren()(0)) + ")&(" +
- timeFilterToPartString(operator.getChildren()(1)) + ")"
- case SQLConstant.KW_OR =>
- "(" + timeFilterToPartString(operator.getChildren()(0)) + ")|(" +
- timeFilterToPartString(operator.getChildren()(1)) + ")"
- case _ =>
- val basicOperator = operator.asInstanceOf[BasicOperator]
- basicOperator.getTokenSymbol + basicOperator.getSeriesValue
- }
- }
-
-
- /**
- * Convert a value filter to QueryConfig's valueFilter parameter. Each query is a cross query.
- *
- * @param operator value filter
- * @param single single series query
- * @return QueryConfig's valueFilter parameter
- */
- private def valueFilterToString(operator: FilterOperator, single: Boolean): String = {
- if (operator == null)
- return "null"
-
- val token = operator.getTokenIntType
- token match {
- case SQLConstant.KW_AND =>
- "[" + valueFilterToString(operator.getChildren()(0), single = true) + "]&[" +
- valueFilterToString(operator.getChildren()(1), single = true) + "]"
- case SQLConstant.KW_OR =>
- "[" + valueFilterToString(operator.getChildren()(0), single = true) + "]|[" +
- valueFilterToString(operator.getChildren()(1), single = true) + "]"
- case _ =>
- val basicOperator = operator.asInstanceOf[BasicOperator]
- val path = basicOperator.getSinglePath
- val res = new StringBuilder
- if (single) {
- res.append("2," + path + "," +
- basicOperator.getTokenSymbol + basicOperator.getSeriesValue)
- }
- else {
- res.append("[2," + path + "," +
- basicOperator.getTokenSymbol + basicOperator.getSeriesValue + "]")
- }
- res.toString()
- }
- }
-
-
- /**
- * Transform sparkSQL's filter binary tree to filterOperator binary tree.
- *
- * @param node filter tree's node
- * @return TSFile filterOperator binary tree
- */
- private def transformFilter(node: Filter): FilterOperator = {
- var operator: FilterOperator = null
+ private def transformFilter(schema: StructType, node: Filter): IExpression = {
+ var filter: IExpression = null
node match {
case node: Not =>
- operator = new FilterOperator(SQLConstant.KW_NOT)
- operator.addChildOPerator(transformFilter(node.child))
- operator
+ throw new Exception("NOT filter is not supported now")
case node: And =>
- operator = new FilterOperator(SQLConstant.KW_AND)
- operator.addChildOPerator(transformFilter(node.left))
- operator.addChildOPerator(transformFilter(node.right))
- operator
+ filter = BinaryExpression.and(transformFilter(schema, node.left), transformFilter(schema, node.right))
+ filter
case node: Or =>
- operator = new FilterOperator(SQLConstant.KW_OR)
- operator.addChildOPerator(transformFilter(node.left))
- operator.addChildOPerator(transformFilter(node.right))
- operator
+ filter = BinaryExpression.or(transformFilter(schema, node.left), transformFilter(schema, node.right))
+ filter
case node: EqualTo =>
- operator = new BasicOperator(SQLConstant.EQUAL, node.attribute, node.value.toString)
- operator
+ if (QueryConstant.RESERVED_TIME.equals(node.attribute.toLowerCase())) {
+ filter = new GlobalTimeExpression(TimeFilter.eq(node.value.asInstanceOf[java.lang.Long]))
+ } else {
+ filter = constructFilter(schema, node.attribute, node.value, FilterTypes.Eq)
+ }
+ filter
case node: LessThan =>
- operator = new BasicOperator(SQLConstant.LESSTHAN, node.attribute, node.value.toString)
- operator
+ if (QueryConstant.RESERVED_TIME.equals(node.attribute.toLowerCase())) {
+ filter = new GlobalTimeExpression(TimeFilter.lt(node.value.asInstanceOf[java.lang.Long]))
+ } else {
+ filter = constructFilter(schema, node.attribute, node.value, FilterTypes.Lt)
+ }
+ filter
case node: LessThanOrEqual =>
- operator = new BasicOperator(SQLConstant.LESSTHANOREQUALTO, node.attribute, node.value.toString)
- operator
+ if (QueryConstant.RESERVED_TIME.equals(node.attribute.toLowerCase())) {
+ filter = new GlobalTimeExpression(TimeFilter.ltEq(node.value.asInstanceOf[java.lang.Long]))
+ } else {
+ filter = constructFilter(schema, node.attribute, node.value, FilterTypes.LtEq)
+ }
+ filter
case node: GreaterThan =>
- operator = new BasicOperator(SQLConstant.GREATERTHAN, node.attribute, node.value.toString)
- operator
+ if (QueryConstant.RESERVED_TIME.equals(node.attribute.toLowerCase())) {
+ filter = new GlobalTimeExpression(TimeFilter.gt(node.value.asInstanceOf[java.lang.Long]))
+ } else {
+ filter = constructFilter(schema, node.attribute, node.value, FilterTypes.Gt)
+ }
+ filter
case node: GreaterThanOrEqual =>
- operator = new BasicOperator(SQLConstant.GREATERTHANOREQUALTO, node.attribute, node.value.toString)
- operator
+ if (QueryConstant.RESERVED_TIME.equals(node.attribute.toLowerCase())) {
+ filter = new GlobalTimeExpression(TimeFilter.gtEq(node.value.asInstanceOf[java.lang.Long]))
+ } else {
+ filter = constructFilter(schema, node.attribute, node.value, FilterTypes.GtEq)
+ }
+ filter
- case _ =>
- throw new Exception("unsupported filter:" + node.toString)
+ case other =>
+ throw new Exception(s"Unsupported filter $other")
}
}
+ def constructFilter(schema: StructType, nodeName: String, nodeValue: Any, filterType: FilterTypes.Value): IExpression = {
+ val fieldNames = schema.fieldNames
+ val index = fieldNames.indexOf(nodeName)
+ if (index == -1) {
+ // placeholder for an invalid filter in the current TsFile
+ val filter = new SingleSeriesExpression(new Path(nodeName), null)
+ filter
+ } else {
+ val dataType = schema.get(index).dataType
+
+ filterType match {
+ case FilterTypes.Eq =>
+ dataType match {
+ case IntegerType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(nodeValue.asInstanceOf[java.lang.Integer]))
+ filter
+ case LongType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(nodeValue.asInstanceOf[java.lang.Long]))
+ filter
+ case FloatType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(nodeValue.asInstanceOf[java.lang.Float]))
+ filter
+ case DoubleType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(nodeValue.asInstanceOf[java.lang.Double]))
+ filter
+ case StringType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(new Binary(nodeValue.toString)))
+ filter
+ case BooleanType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.eq(nodeValue.asInstanceOf[java.lang.Boolean]))
+ filter
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ case FilterTypes.Gt =>
+ dataType match {
+ case IntegerType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gt(nodeValue.asInstanceOf[java.lang.Integer]))
+ filter
+ case LongType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gt(nodeValue.asInstanceOf[java.lang.Long]))
+ filter
+ case FloatType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gt(nodeValue.asInstanceOf[java.lang.Float]))
+ filter
+ case DoubleType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gt(nodeValue.asInstanceOf[java.lang.Double]))
+ filter
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ case FilterTypes.GtEq =>
+ dataType match {
+ case IntegerType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gtEq(nodeValue.asInstanceOf[java.lang.Integer]))
+ filter
+ case LongType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gtEq(nodeValue.asInstanceOf[java.lang.Long]))
+ filter
+ case FloatType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gtEq(nodeValue.asInstanceOf[java.lang.Float]))
+ filter
+ case DoubleType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.gtEq(nodeValue.asInstanceOf[java.lang.Double]))
+ filter
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ case FilterTypes.Lt =>
+ dataType match {
+ case IntegerType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.lt(nodeValue.asInstanceOf[java.lang.Integer]))
+ filter
+ case LongType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.lt(nodeValue.asInstanceOf[java.lang.Long]))
+ filter
+ case FloatType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.lt(nodeValue.asInstanceOf[java.lang.Float]))
+ filter
+ case DoubleType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.lt(nodeValue.asInstanceOf[java.lang.Double]))
+ filter
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ case FilterTypes.LtEq =>
+ dataType match {
+ case IntegerType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.ltEq(nodeValue.asInstanceOf[java.lang.Integer]))
+ filter
+ case LongType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.ltEq(nodeValue.asInstanceOf[java.lang.Long]))
+ filter
+ case FloatType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.ltEq(nodeValue.asInstanceOf[java.lang.Float]))
+ filter
+ case DoubleType =>
+ val filter = new SingleSeriesExpression(new Path(nodeName),
+ ValueFilter.ltEq(nodeValue.asInstanceOf[java.lang.Double]))
+ filter
+ case other => throw new UnsupportedOperationException(s"Unsupported type $other")
+ }
+ }
+ }
+ }
+
+ object FilterTypes extends Enumeration {
+ val Eq, Gt, GtEq, Lt, LtEq = Value
+ }
+
class SparkSqlFilterException(message: String, cause: Throwable)
extends Exception(message, cause) {
def this(message: String) = this(message, null)
@@ -462,5 +589,4 @@ object Converter {
case class SchemaType(dataType: DataType, nullable: Boolean)
-
-}
\ No newline at end of file
+}
diff --git a/spark/src/main/scala/org/apache/iotdb/tsfile/DefaultSource.scala b/spark/src/main/scala/org/apache/iotdb/tsfile/DefaultSource.scala
index 85bed7c..249f511 100755
--- a/spark/src/main/scala/org/apache/iotdb/tsfile/DefaultSource.scala
+++ b/spark/src/main/scala/org/apache/iotdb/tsfile/DefaultSource.scala
@@ -1,28 +1,44 @@
/**
- * 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.
- */
+ * 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.iotdb.tsfile
import java.io.{ObjectInputStream, ObjectOutputStream, _}
import java.net.URI
-import java.util
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, Path}
+import org.apache.hadoop.mapreduce.Job
+import org.apache.iotdb.tsfile.DefaultSource.SerializableConfiguration
+import org.apache.iotdb.tsfile.common.constant.QueryConstant
+import org.apache.iotdb.tsfile.io.HDFSInput
+import org.apache.iotdb.tsfile.read.common.Field
+import org.apache.iotdb.tsfile.read.{ReadOnlyTsFile, TsFileSequenceReader}
+import org.apache.spark.TaskContext
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.InternalRow
+import org.apache.spark.sql.catalyst.encoders.RowEncoder
+import org.apache.spark.sql.catalyst.expressions.GenericRow
+import org.apache.spark.sql.execution.datasources.{FileFormat, OutputWriterFactory, PartitionedFile}
+import org.apache.spark.sql.sources.{DataSourceRegister, Filter}
+import org.apache.spark.sql.types._
+import org.slf4j.LoggerFactory
private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
@@ -43,26 +59,13 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
//get union series in TsFile
val tsfileSchema = Converter.getUnionSeries(files, conf)
- DefaultSource.columnNames.clear()
-
- //unfold delta_object
- if (options.contains(SQLConstant.DELTA_OBJECT_NAME)) {
- val columns = options(SQLConstant.DELTA_OBJECT_NAME).split(SQLConstant.REGEX_PATH_SEPARATOR)
- columns.foreach(f => {
- DefaultSource.columnNames += f
- })
- } else {
- //using delta_object
- DefaultSource.columnNames += SQLConstant.RESERVED_DELTA_OBJECT
- }
-
- Converter.toSqlSchema(tsfileSchema, DefaultSource.columnNames)
+ Converter.toSqlSchema(tsfileSchema)
}
override def isSplitable(
sparkSession: SparkSession,
options: Map[String, String],
- path: Path): Boolean = {
+ path: org.apache.hadoop.fs.Path): Boolean = {
true
}
@@ -82,7 +85,9 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
log.info(file.toString())
val conf = broadcastedConf.value.value
- val in = new HDFSInputStream(new Path(new URI(file.filePath)), conf)
+ val in = new HDFSInput(new Path(new URI(file.filePath)), conf)
+
+ val reader: TsFileSequenceReader = new TsFileSequenceReader(in)
Option(TaskContext.get()).foreach { taskContext => {
taskContext.addTaskCompletionListener { _ => in.close() }
@@ -90,44 +95,20 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
}
}
- val parameters = new util.HashMap[java.lang.String, java.lang.Long]()
- parameters.put(QueryConstant.PARTITION_START_OFFSET, file.start.asInstanceOf[java.lang.Long])
- parameters.put(QueryConstant.PARTITION_END_OFFSET, (file.start + file.length).asInstanceOf[java.lang.Long])
-
- //convert tsfile query to QueryConfigs
- val queryConfigs = Converter.toQueryConfigs(in, requiredSchema, filters, DefaultSource.columnNames,
- file.start.asInstanceOf[java.lang.Long], (file.start + file.length).asInstanceOf[java.lang.Long])
+ val params = new java.util.HashMap[java.lang.String, java.lang.Long]()
+ params.put(QueryConstant.PARTITION_START_OFFSET, file.start.asInstanceOf[java.lang.Long])
+ params.put(QueryConstant.PARTITION_END_OFFSET, (file.start + file.length).asInstanceOf[java.lang.Long])
- //use QueryConfigs to query data in tsfile
- val dataSets = Executor.query(in, queryConfigs.toList, parameters)
-
- case class Record(record: RowRecord, index: Int)
-
- implicit object RowRecordOrdering extends Ordering[Record] {
- override def compare(r1: Record, r2: Record): Int = {
- if (r1.record.timestamp == r2.record.timestamp) {
- r1.record.getFields.get(0).deltaObjectId.compareTo(r2.record.getFields.get(0).deltaObjectId)
- } else if (r1.record.timestamp < r2.record.timestamp) {
- 1
- } else {
- -1
- }
- }
- }
+ val tsFileMetaData = reader.readFileMetadata
- val priorityQueue = new mutable.PriorityQueue[Record]()
+ // get queriedSchema from requiredSchema
+ var queriedSchema = Converter.prepSchema(requiredSchema, tsFileMetaData)
- //init priorityQueue with first record of each dataSet
- var queryDataSet: QueryDataSet = null
- for (i <- 0 until dataSets.size()) {
- queryDataSet = dataSets(i)
- if (queryDataSet.hasNextRecord) {
- val rowRecord = queryDataSet.getNextRecord
- priorityQueue.enqueue(Record(rowRecord, i))
- }
- }
+ // construct queryExpression based on queriedSchema and filters
+ val queryExpression = Converter.toQueryExpression(queriedSchema, filters)
- var curRecord: Record = null
+ val readTsFile: ReadOnlyTsFile = new ReadOnlyTsFile(reader, params)
+ val queryDataSet = readTsFile.query(queryExpression)
new Iterator[InternalRow] {
private val rowBuffer = Array.fill[Any](requiredSchema.length)(null)
@@ -137,51 +118,29 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
// Used to convert `Row`s containing data columns into `InternalRow`s.
private val encoderForDataColumns = RowEncoder(requiredSchema)
- private var deltaObjectId = "null"
-
override def hasNext: Boolean = {
- var hasNext = false
-
- while (priorityQueue.nonEmpty && !hasNext) {
- //get a record from priorityQueue
- val tmpRecord = priorityQueue.dequeue()
- //insert a record to priorityQueue
- if (dataSets(tmpRecord.index).hasNextRecord) {
- priorityQueue.enqueue(Record(dataSets(tmpRecord.index).getNextRecord, tmpRecord.index))
- }
-
- if (curRecord == null || tmpRecord.record.timestamp != curRecord.record.timestamp ||
- !tmpRecord.record.getFields.get(0).deltaObjectId.equals(curRecord.record.getFields.get(0).deltaObjectId)) {
- curRecord = tmpRecord
- deltaObjectId = curRecord.record.getFields.get(0).deltaObjectId
- hasNext = true
- }
- }
-
+ val hasNext = queryDataSet.hasNext
hasNext
}
override def next(): InternalRow = {
- val fields = new scala.collection.mutable.HashMap[String, Field]()
- for (i <- 0 until curRecord.record.fields.size()) {
- val field = curRecord.record.fields.get(i)
- fields.put(field.measurementId, field)
- }
+ val curRecord = queryDataSet.next()
+ val fields = curRecord.getFields
+ val paths = queryDataSet.getPaths
//index in one required row
var index = 0
requiredSchema.foreach((field: StructField) => {
- if (field.name == SQLConstant.RESERVED_TIME) {
- rowBuffer(index) = curRecord.record.timestamp
- } else if (field.name == SQLConstant.RESERVED_DELTA_OBJECT) {
- rowBuffer(index) = deltaObjectId
- } else if (DefaultSource.columnNames.contains(field.name)) {
- val columnIndex = DefaultSource.columnNames.indexOf(field.name)
- val columns = deltaObjectId.split(SQLConstant.REGEX_PATH_SEPARATOR)
- rowBuffer(index) = columns(columnIndex)
+ if (field.name == QueryConstant.RESERVED_TIME) {
+ rowBuffer(index) = curRecord.getTimestamp
} else {
- rowBuffer(index) = Converter.toSqlValue(fields.getOrElse(field.name, null))
+ val pos = paths.indexOf(new org.apache.iotdb.tsfile.read.common.Path(field.name))
+ var curField: Field = null
+ if (pos != -1) {
+ curField = fields.get(pos)
+ }
+ rowBuffer(index) = Converter.toSqlValue(curField)
}
index += 1
})
@@ -198,20 +157,8 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
job: Job,
options: Map[String, String],
dataSchema: StructType): OutputWriterFactory = {
- DefaultSource.columnNames.clear()
-
- //unfold delta_object
- if (options.contains(SQLConstant.DELTA_OBJECT_NAME)) {
- val columns = options(SQLConstant.DELTA_OBJECT_NAME).split(SQLConstant.REGEX_PATH_SEPARATOR)
- columns.foreach(f => {
- DefaultSource.columnNames += f
- })
- } else {
- //using delta_object
- DefaultSource.columnNames += SQLConstant.RESERVED_DELTA_OBJECT
- }
- new TsFileWriterFactory(options, DefaultSource.columnNames)
+ new TsFileWriterFactory(options)
}
class TSFileDataSourceException(message: String, cause: Throwable)
@@ -224,7 +171,6 @@ private[tsfile] class DefaultSource extends FileFormat with DataSourceRegister {
private[tsfile] object DefaultSource {
val path = "path"
- val columnNames = new ArrayBuffer[String]()
class SerializableConfiguration(@transient var value: Configuration) extends Serializable {
private def writeObject(out: ObjectOutputStream): Unit = {
diff --git a/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileOutputWriter.scala b/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileOutputWriter.scala
index c4cbb9b..0ced194 100644
--- a/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileOutputWriter.scala
+++ b/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileOutputWriter.scala
@@ -1,40 +1,48 @@
/**
- * 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.
- */
-
+ * 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.iotdb.tsfile
+import org.apache.hadoop.io.NullWritable
+import org.apache.hadoop.mapreduce.{RecordWriter, TaskAttemptContext}
+import org.apache.iotdb.tsfile.io.TsFileOutputFormat
+import org.apache.iotdb.tsfile.write.record.TSRecord
+import org.apache.spark.sql.Row
+import org.apache.spark.sql.execution.datasources.OutputWriter
+import org.apache.spark.sql.types._
+
private[tsfile] class TsFileOutputWriter(
pathStr: String,
- columnNames: ArrayBuffer[String],
dataSchema: StructType,
options: Map[String, String],
context: TaskAttemptContext) extends OutputWriter {
private val recordWriter: RecordWriter[NullWritable, TSRecord] = {
- val fileSchema = Converter.toTsFileSchema(columnNames, dataSchema, options)
+ val fileSchema = Converter.toTsFileSchema(dataSchema, options)
new TsFileOutputFormat(fileSchema).getRecordWriter(context)
}
override def write(row: Row): Unit = {
if (row != null) {
- val tsRecord = Converter.toTsRecord(columnNames, row)
- recordWriter.write(NullWritable.get(), tsRecord)
+ val tsRecord = Converter.toTsRecord(row)
+ tsRecord.foreach(r => {
+ recordWriter.write(NullWritable.get(), r)
+ })
}
}
diff --git a/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileWriterFactory.scala b/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileWriterFactory.scala
index 3fef0a0..d78d093 100644
--- a/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileWriterFactory.scala
+++ b/spark/src/main/scala/org/apache/iotdb/tsfile/TsFileWriterFactory.scala
@@ -1,31 +1,35 @@
/**
- * 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.
- */
+ * 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.iotdb.tsfile
-private[tsfile] class TsFileWriterFactory(options: Map[String, String], columnNames: ArrayBuffer[String]) extends OutputWriterFactory {
+import org.apache.hadoop.mapreduce.TaskAttemptContext
+import org.apache.spark.sql.execution.datasources.{OutputWriter, OutputWriterFactory}
+import org.apache.spark.sql.types.StructType
+
+private[tsfile] class TsFileWriterFactory(options: Map[String, String]) extends OutputWriterFactory {
override def newInstance(
path: String,
bucketId: Option[Int],
dataSchema: StructType,
context: TaskAttemptContext): OutputWriter = {
- new TsFileOutputWriter(path, columnNames, dataSchema, options, context)
+ new TsFileOutputWriter(path, dataSchema, options, context)
}
}
diff --git a/spark/src/main/scala/org/apache/iotdb/tsfile/package.scala b/spark/src/main/scala/org/apache/iotdb/tsfile/package.scala
index 99753c8..e79e6a3 100755
--- a/spark/src/main/scala/org/apache/iotdb/tsfile/package.scala
+++ b/spark/src/main/scala/org/apache/iotdb/tsfile/package.scala
@@ -1,24 +1,26 @@
/**
- * 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.
- */
+ * 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.iotdb
+import org.apache.spark.sql.{DataFrame, DataFrameReader, DataFrameWriter}
+
package object tsfile {
/**
diff --git a/spark/src/test/resources/test.tsfile b/spark/src/test/resources/test.tsfile
deleted file mode 100644
index 5ea2034..0000000
Binary files a/spark/src/test/resources/test.tsfile and /dev/null differ
diff --git a/spark/src/test/scala/cn/edu/tsinghua/tsfile/ConverterTest.scala b/spark/src/test/scala/cn/edu/tsinghua/tsfile/ConverterTest.scala
deleted file mode 100644
index 1604266..0000000
--- a/spark/src/test/scala/cn/edu/tsinghua/tsfile/ConverterTest.scala
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * 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.iotdb.tsfile
-
-import java.io.File
-import java.util
-
-
-class ConverterTest extends FunSuite with BeforeAndAfterAll {
-
- private val tsfilePath: String = "src/test/resources/test.tsfile"
-
- override protected def beforeAll(): Unit = {
- super.beforeAll()
- val tsfile = new File(tsfilePath)
- if (!tsfile.getParentFile.exists())
- tsfile.mkdirs()
- new CreateTSFile().createTSFile1(tsfilePath)
- }
-
- override protected def afterAll(): Unit = {
- super.afterAll()
- }
-
- test("testToQueryConfigs") {
- val in = new TsRandomAccessLocalFileReader(tsfilePath)
-
- val requiredSchema = StructType(Seq(
- StructField("s1", IntegerType, nullable = true)
- ))
-
- val filters = new ListBuffer[Filter]()
- filters += LessThan("time", 80)
- filters += GreaterThan("time", 50)
- filters += Or(LessThan("s1", 50), GreaterThan("s1", 80))
- val columns = new ArrayBuffer[String]()
- columns += SQLConstant.RESERVED_DELTA_OBJECT
- val queryConfigs = Converter.toQueryConfigs(in, requiredSchema, filters, columns, "0".toLong, "749".toLong)
-
- val queryConfig0 = new QueryConfig("root.car.d2.s1", "0,(<80)&(>50)", "null", "2,root.car.d2.s1,<50")
- val queryConfig1 = new QueryConfig("root.car.d1.s1", "0,(<80)&(>50)", "null", "2,root.car.d1.s1,<50")
- val queryConfig2 = new QueryConfig("root.car.d2.s1", "0,(<80)&(>50)", "null", "2,root.car.d2.s1,>80")
- val queryConfig3 = new QueryConfig("root.car.d1.s1", "0,(<80)&(>50)", "null", "2,root.car.d1.s1,>80")
-
- Assert.assertEquals(4, queryConfigs.length)
- Assert.assertEquals(queryConfig0.getSelectColumns, queryConfigs(0).getSelectColumns)
- Assert.assertEquals(queryConfig0.getValueFilter, queryConfigs(0).getValueFilter)
- Assert.assertEquals(queryConfig0.getTimeFilter, queryConfigs(0).getTimeFilter)
-
- Assert.assertEquals(queryConfig1.getSelectColumns, queryConfigs(1).getSelectColumns)
- Assert.assertEquals(queryConfig1.getValueFilter, queryConfigs(1).getValueFilter)
- Assert.assertEquals(queryConfig1.getTimeFilter, queryConfigs(1).getTimeFilter)
-
- Assert.assertEquals(queryConfig2.getSelectColumns, queryConfigs(2).getSelectColumns)
- Assert.assertEquals(queryConfig2.getValueFilter, queryConfigs(2).getValueFilter)
- Assert.assertEquals(queryConfig2.getTimeFilter, queryConfigs(2).getTimeFilter)
-
- Assert.assertEquals(queryConfig3.getSelectColumns, queryConfigs(3).getSelectColumns)
- Assert.assertEquals(queryConfig3.getValueFilter, queryConfigs(3).getValueFilter)
- Assert.assertEquals(queryConfig3.getTimeFilter, queryConfigs(3).getTimeFilter)
- }
-
- test("testToSparkSqlSchema") {
- val fields: util.ArrayList[SeriesSchema] = new util.ArrayList[SeriesSchema]()
- fields.add(new SeriesSchema("s1", TSDataType.INT32, TSEncoding.PLAIN))
- fields.add(new SeriesSchema("s2", TSDataType.INT64, TSEncoding.PLAIN))
- fields.add(new SeriesSchema("s3", TSDataType.FLOAT, TSEncoding.PLAIN))
- fields.add(new SeriesSchema("s4", TSDataType.DOUBLE, TSEncoding.PLAIN))
- fields.add(new SeriesSchema("s5", TSDataType.BOOLEAN, TSEncoding.PLAIN))
- fields.add(new SeriesSchema("s6", TSDataType.TEXT, TSEncoding.PLAIN))
- val columns = new ArrayBuffer[String]()
- columns += SQLConstant.RESERVED_DELTA_OBJECT
- val sqlSchema = Converter.toSqlSchema(fields, columns)
-
- val expectedFields = Array(
- StructField(SQLConstant.RESERVED_TIME, LongType, nullable = false),
- StructField(SQLConstant.RESERVED_DELTA_OBJECT, StringType, nullable = false),
- StructField("s1", IntegerType, nullable = true),
- StructField("s2", LongType, nullable = true),
- StructField("s3", FloatType, nullable = true),
- StructField("s4", DoubleType, nullable = true),
- StructField("s5", BooleanType, nullable = true),
- StructField("s6", StringType, nullable = true)
- )
- val expectedType = StructType(expectedFields)
- val expectedSchema = StructType(expectedType.toList)
-
- Assert.assertEquals(expectedSchema, sqlSchema.get)
- }
-
- test("testToSqlValue") {
- val boolField = new Field(TSDataType.BOOLEAN, "s1")
- boolField.setBoolV(true)
- val intField = new Field(TSDataType.INT32, "s1")
- intField.setIntV(32)
- val longField = new Field(TSDataType.INT64, "s1")
- longField.setLongV(64l)
- val floatField = new Field(TSDataType.FLOAT, "s1")
- floatField.setFloatV(3.14f)
- val doubleField = new Field(TSDataType.DOUBLE, "s1")
- doubleField.setDoubleV(0.618d)
- val stringField = new Field(TSDataType.TEXT, "s1")
- stringField.setBinaryV(new Binary("pass"))
-
- Assert.assertEquals(Converter.toSqlValue(boolField), true)
- Assert.assertEquals(Converter.toSqlValue(intField), 32)
- Assert.assertEquals(Converter.toSqlValue(longField), 64l)
- Assert.assertEquals(Converter.toSqlValue(floatField), 3.14f)
- Assert.assertEquals(Converter.toSqlValue(doubleField), 0.618d)
- Assert.assertEquals(Converter.toSqlValue(stringField), "pass")
- }
-
-}
diff --git a/spark/src/test/scala/cn/edu/tsinghua/tsfile/TSFileSuit.scala b/spark/src/test/scala/cn/edu/tsinghua/tsfile/TSFileSuit.scala
deleted file mode 100644
index 9b897db..0000000
--- a/spark/src/test/scala/cn/edu/tsinghua/tsfile/TSFileSuit.scala
+++ /dev/null
@@ -1,194 +0,0 @@
-/**
- * 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.iotdb.tsfile
-
-import java.io.File
-
-
-class TSFileSuit extends FunSuite with BeforeAndAfterAll {
-
- private val resourcesFolder = "src/test/resources"
- private val tsfileFolder = "src/test/resources/tsfile"
- private val tsfile1 = "src/test/resources/tsfile/test1.tsfile"
- private val tsfile2 = "src/test/resources/tsfile/test2.tsfile"
- private val outputPath = "src/test/resources/output"
- private val outputPathFile = outputPath + "/part-m-00000"
- private val outputPath2 = "src/test/resources/output2"
- private val outputPathFile2 = outputPath2 + "/part-m-00000"
- private var spark: SparkSession = _
-
- def deleteDir(dir: File): Unit = {
- if (dir.isDirectory) {
- dir.list().foreach(f => {
- deleteDir(new File(dir, f))
- })
- }
- dir.delete()
-
- }
-
- override protected def beforeAll(): Unit = {
- super.beforeAll()
- val resources = new File(resourcesFolder)
- if (!resources.exists())
- resources.mkdirs()
- val tsfile_folder = new File(tsfileFolder)
- if (!tsfile_folder.exists())
- tsfile_folder.mkdirs()
- val output = new File(outputPath)
- if (output.exists())
- deleteDir(output)
- val output2 = new File(outputPath2)
- if (output2.exists())
- deleteDir(output2)
- new CreateTSFile().createTSFile1(tsfile1)
- new CreateTSFile().createTSFile2(tsfile2)
- spark = SparkSession
- .builder()
- .config("spark.master", "local")
- .appName("TSFile test")
- .getOrCreate()
- }
-
- override protected def afterAll(): Unit = {
- val out = new File(outputPath)
- deleteDir(out)
- val out2 = new File(outputPath2)
- deleteDir(out2)
- try {
- spark.sparkContext.stop()
- } finally {
- super.afterAll()
- }
- }
-
-
- test("writer") {
- val df = spark.read.tsfile(tsfile1)
- df.show()
- df.write.tsfile(outputPath)
- val newDf = spark.read.tsfile(outputPathFile)
- newDf.show()
- Assert.assertEquals(newDf.collectAsList(), df.collectAsList())
- }
-
- test("test write options") {
- val df = spark.read.option("delta_object_name", "root.carId.deviceId").tsfile(tsfile1)
- df.write.option("delta_object_name", "root.carId.deviceId") tsfile (outputPath2)
- val newDf = spark.read.option("delta_object_name", "root.carId.deviceId").tsfile(outputPathFile2)
- newDf.show()
- Assert.assertEquals(newDf.collectAsList(), df.collectAsList())
- }
-
- test("test read options") {
- val options = new mutable.HashMap[String, String]()
- options.put(SQLConstant.DELTA_OBJECT_NAME, "root.carId.deviceId")
- val df = spark.read.options(options).tsfile(tsfile1)
- df.createOrReplaceTempView("tsfile_table")
-
- spark.sql("select * from tsfile_table where deviceId = 'd1' and carId = 'car' and time < 10").show()
- val newDf = spark.sql("select * from tsfile_table where deviceId = 'd1'")
- Assert.assertEquals(4, newDf.count())
- }
-
- test("tsfile_qp") {
- val df = spark.read.tsfile(tsfileFolder)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select s1,s2 from tsfile_table where delta_object = 'root.car.d1' and time <= 10 and (time > 5 or s1 > 10)")
- Assert.assertEquals(0, newDf.count())
- }
-
- test("testMultiFilesNoneExistDelta_object") {
- val df = spark.read.tsfile(tsfileFolder)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select * from tsfile_table where delta_object = 'd4'")
- Assert.assertEquals(0, newDf.count())
- }
-
- test("testMultiFilesWithFilterOr") {
- val df = spark.read.tsfile(tsfileFolder)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select * from tsfile_table where s1 < 2 or s2 > 60")
- Assert.assertEquals(4, newDf.count())
- }
-
- test("testMultiFilesWithFilterAnd") {
- val df = spark.read.tsfile(tsfileFolder)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select * from tsfile_table where s2 > 20 and s1 < 5")
- Assert.assertEquals(2, newDf.count())
- }
-
- test("testMultiFilesSelect*") {
- val df = spark.read.tsfile(tsfileFolder)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select * from tsfile_table")
- Assert.assertEquals(16, newDf.count())
- }
-
- test("testCount") {
- val df = spark.read.tsfile(tsfile1)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select count(*) from tsfile_table")
- Assert.assertEquals(8, newDf.head().apply(0).asInstanceOf[Long])
- }
-
- test("testSelect *") {
- val df = spark.read.tsfile(tsfile1)
- df.createOrReplaceTempView("tsfile_table")
- val newDf = spark.sql("select * from tsfile_table")
- val count = newDf.count()
- Assert.assertEquals(8, count)
- }
-
- test("testQueryData1") {
- val df = spark.read.tsfile(tsfile1)
- df.createOrReplaceTempView("tsfile_table")
-
- val newDf = spark.sql("select s1, s3 from tsfile_table where s1 > 4 and delta_object = 'root.car.d2'").cache()
- val count = newDf.count()
- Assert.assertEquals(4, count)
- }
-
- test("testQueryDataComplex2") {
- val df = spark.read.tsfile(tsfile1)
- df.createOrReplaceTempView("tsfile_table")
-
- val newDf = spark.sql("select * from tsfile_table where s1 <4 and delta_object = 'root.car.d1' or s1 > 5 and delta_object = 'root.car.d2'").cache()
- val count = newDf.count()
- Assert.assertEquals(6, count)
- }
-
- test("testQuerySchema") {
- val df = spark.read.format("org.apache.iotdb.tsfile").load(tsfile1)
-
- val expected = StructType(Seq(
- StructField(SQLConstant.RESERVED_TIME, LongType, nullable = true),
- StructField(SQLConstant.RESERVED_DELTA_OBJECT, StringType, nullable = true),
- StructField("s3", FloatType, nullable = true),
- StructField("s4", DoubleType, nullable = true),
- StructField("s5", StringType, nullable = true),
- StructField("s1", IntegerType, nullable = true),
- StructField("s2", LongType, nullable = true)
- ))
- Assert.assertEquals(expected, df.schema)
- }
-
-}
\ No newline at end of file
diff --git a/spark/src/test/scala/org/apache/iotdb/tool/TsFileExample.java b/spark/src/test/scala/org/apache/iotdb/tool/TsFileExample.java
new file mode 100644
index 0000000..1da7b77
--- /dev/null
+++ b/spark/src/test/scala/org/apache/iotdb/tool/TsFileExample.java
@@ -0,0 +1,106 @@
+/**
+ * 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.iotdb.tool;
+
+import java.io.File;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.write.TsFileWriter;
+import org.apache.iotdb.tsfile.write.record.TSRecord;
+import org.apache.iotdb.tsfile.write.record.datapoint.BooleanDataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.FloatDataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.StringDataPoint;
+import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
+
+/**
+ * Write an example TsFile as shown in README.
+ */
+public class TsFileExample {
+
+ public static void create(String tsfilePath) throws Exception {
+ File f = new File(tsfilePath);
+ if (f.exists()) {
+ f.delete();
+ }
+ TsFileWriter tsFileWriter = new TsFileWriter(f);
+
+ // add measurements into file schema
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("status", TSDataType.BOOLEAN, TSEncoding.PLAIN));
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("temperature", TSDataType.FLOAT, TSEncoding.RLE));
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("hardware", TSDataType.TEXT, TSEncoding.PLAIN));
+
+ // construct TSRecord
+ TSRecord tsRecord = new TSRecord(1, "root.ln.wf01.wt01");
+ DataPoint dPoint1 = new FloatDataPoint("temperature", 2.2f);
+ DataPoint dPoint2 = new BooleanDataPoint("status", true);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(2, "root.ln.wf01.wt01");
+ dPoint1 = new FloatDataPoint("temperature", 2.2f);
+ tsRecord.addTuple(dPoint1);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(3, "root.ln.wf01.wt01");
+ dPoint1 = new BooleanDataPoint("status", true);
+ dPoint2 = new FloatDataPoint("temperature", 2.1f);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(5, "root.ln.wf01.wt01");
+ dPoint1 = new BooleanDataPoint("status", false);
+ tsRecord.addTuple(dPoint1);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(1, "root.ln.wf02.wt02");
+ dPoint1 = new BooleanDataPoint("status", true);
+ tsRecord.addTuple(dPoint1);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(2, "root.ln.wf02.wt02");
+ dPoint1 = new BooleanDataPoint("status", false);
+ dPoint2 = new StringDataPoint("hardware", new Binary("aaa"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(4, "root.ln.wf02.wt02");
+ dPoint1 = new BooleanDataPoint("status", true);
+ dPoint2 = new StringDataPoint("hardware", new Binary("bbb"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(6, "root.ln.wf02.wt02");
+ dPoint1 = new StringDataPoint("hardware", new Binary("ccc"));
+ tsRecord.addTuple(dPoint1);
+ tsFileWriter.write(tsRecord);
+
+ // close TsFile
+ tsFileWriter.close();
+ }
+
+}
diff --git a/spark/src/test/scala/org/apache/iotdb/tool/TsFileWrite.java b/spark/src/test/scala/org/apache/iotdb/tool/TsFileWrite.java
new file mode 100644
index 0000000..fb73f1b
--- /dev/null
+++ b/spark/src/test/scala/org/apache/iotdb/tool/TsFileWrite.java
@@ -0,0 +1,215 @@
+/**
+ * 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.iotdb.tool;
+
+import java.io.File;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
+import org.apache.iotdb.tsfile.file.metadata.enums.TSEncoding;
+import org.apache.iotdb.tsfile.utils.Binary;
+import org.apache.iotdb.tsfile.write.TsFileWriter;
+import org.apache.iotdb.tsfile.write.record.TSRecord;
+import org.apache.iotdb.tsfile.write.record.datapoint.BooleanDataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.FloatDataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.IntDataPoint;
+import org.apache.iotdb.tsfile.write.record.datapoint.StringDataPoint;
+import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
+
+/**
+ * An example of writing data to TsFile
+ */
+public class TsFileWrite {
+
+ public static int largeNum = 1024 * 1024;
+
+ public void create1(String tsfilePath) throws Exception {
+ File f = new File(tsfilePath);
+ if (f.exists()) {
+ f.delete();
+ }
+ TsFileWriter tsFileWriter = new TsFileWriter(f);
+
+ // add measurements into file schema
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_1", TSDataType.FLOAT, TSEncoding.RLE));
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_2", TSDataType.INT32, TSEncoding.TS_2DIFF));
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_3", TSDataType.INT32, TSEncoding.TS_2DIFF));
+
+ // construct TSRecord
+ TSRecord tsRecord = new TSRecord(1, "device_1");
+ DataPoint dPoint1 = new FloatDataPoint("sensor_1", 1.2f);
+ DataPoint dPoint2 = new IntDataPoint("sensor_2", 20);
+ DataPoint dPoint3;
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+
+ // write a TSRecord to TsFile
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(2, "device_1");
+ dPoint2 = new IntDataPoint("sensor_2", 20);
+ dPoint3 = new IntDataPoint("sensor_3", 50);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(3, "device_1");
+ dPoint1 = new FloatDataPoint("sensor_1", 1.4f);
+ dPoint2 = new IntDataPoint("sensor_2", 21);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(4, "device_1");
+ dPoint1 = new FloatDataPoint("sensor_1", 1.2f);
+ dPoint2 = new IntDataPoint("sensor_2", 20);
+ dPoint3 = new IntDataPoint("sensor_3", 51);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(6, "device_1");
+ dPoint1 = new FloatDataPoint("sensor_1", 7.2f);
+ dPoint2 = new IntDataPoint("sensor_2", 10);
+ dPoint3 = new IntDataPoint("sensor_3", 11);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(7, "device_1");
+ dPoint1 = new FloatDataPoint("sensor_1", 6.2f);
+ dPoint2 = new IntDataPoint("sensor_2", 20);
+ dPoint3 = new IntDataPoint("sensor_3", 21);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(8, "device_1");
+ dPoint1 = new FloatDataPoint("sensor_1", 9.2f);
+ dPoint2 = new IntDataPoint("sensor_2", 30);
+ dPoint3 = new IntDataPoint("sensor_3", 31);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(1, "device_2");
+ dPoint1 = new FloatDataPoint("sensor_1", 2.3f);
+ dPoint2 = new IntDataPoint("sensor_2", 11);
+ dPoint3 = new IntDataPoint("sensor_3", 19);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(2, "device_2");
+ dPoint1 = new FloatDataPoint("sensor_1", 25.4f);
+ dPoint2 = new IntDataPoint("sensor_2", 10);
+ dPoint3 = new IntDataPoint("sensor_3", 21);
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsRecord.addTuple(dPoint3);
+ tsFileWriter.write(tsRecord);
+
+ // close TsFile
+ tsFileWriter.close();
+ }
+
+ public void create2(String tsfilePath) throws Exception {
+ File f = new File(tsfilePath);
+ if (f.exists()) {
+ f.delete();
+ }
+ TsFileWriter tsFileWriter = new TsFileWriter(f);
+
+ // add measurements into file schema
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_1", TSDataType.FLOAT, TSEncoding.RLE));
+ for (long i = 0; i < largeNum; i++) {
+ // construct TSRecord
+ TSRecord tsRecord = new TSRecord(i, "device_1");
+ DataPoint dPoint1 = new FloatDataPoint("sensor_1", (float) i);
+ tsRecord.addTuple(dPoint1);
+ // write a TSRecord to TsFile
+ tsFileWriter.write(tsRecord);
+ }
+ // close TsFile
+ tsFileWriter.close();
+ }
+
+ public void create3(String tsfilePath) throws Exception {
+ File f = new File(tsfilePath);
+ if (f.exists()) {
+ f.delete();
+ }
+ TsFileWriter tsFileWriter = new TsFileWriter(f);
+
+ // add measurements into file schema
+ // NOTE the sensors here are different from those defined in create1 and
+ // create2 function, despite their names are the same.
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_1", TSDataType.BOOLEAN, TSEncoding.RLE));
+ tsFileWriter
+ .addMeasurement(new MeasurementSchema("sensor_2", TSDataType.TEXT, TSEncoding.PLAIN));
+
+ // construct TSRecord
+ TSRecord tsRecord = new TSRecord(1, "device_1");
+ DataPoint dPoint1 = new BooleanDataPoint("sensor_1", true);
+ DataPoint dPoint2 = new StringDataPoint("sensor_2", new Binary("Monday"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+
+ // write a TSRecord to TsFile
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(2, "device_1");
+ dPoint2 = new StringDataPoint("sensor_2", new Binary("Tuesday"));
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(3, "device_1");
+ dPoint1 = new BooleanDataPoint("sensor_1", false);
+ dPoint2 = new StringDataPoint("sensor_2", new Binary("Wednesday"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(4, "device_1");
+ dPoint1 = new BooleanDataPoint("sensor_1", false);
+ dPoint2 = new StringDataPoint("sensor_2", new Binary("Thursday"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ tsRecord = new TSRecord(6, "device_1");
+ dPoint1 = new BooleanDataPoint("sensor_1", true);
+ dPoint2 = new StringDataPoint("sensor_2", new Binary("Saturday"));
+ tsRecord.addTuple(dPoint1);
+ tsRecord.addTuple(dPoint2);
+ tsFileWriter.write(tsRecord);
+
+ // close TsFile
+ tsFileWriter.close();
+ }
+}
\ No newline at end of file
diff --git a/spark/src/test/scala/org/apache/iotdb/tsfile/ConverterTest.scala b/spark/src/test/scala/org/apache/iotdb/tsfile/ConverterTest.scala
new file mode 100644
index 0000000..9f2f36d
--- /dev/null
+++ b/spark/src/test/scala/org/apache/iotdb/tsfile/ConverterTest.scala
@@ -0,0 +1,266 @@
+/**
+ * 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.iotdb.tsfile
+
+import java.io.File
+import java.net.URI
+import java.util
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileStatus, FileSystem, Path}
+import org.apache.iotdb.tool.TsFileWrite
+import org.apache.iotdb.tsfile.common.constant.QueryConstant
+import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType
+import org.apache.iotdb.tsfile.io.HDFSInput
+import org.apache.iotdb.tsfile.read.TsFileSequenceReader
+import org.apache.iotdb.tsfile.read.common.Field
+import org.apache.iotdb.tsfile.utils.Binary
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
+import org.apache.spark.sql.sources._
+import org.apache.spark.sql.types._
+import org.junit.Assert
+import org.scalatest.{BeforeAndAfterAll, FunSuite}
+
+class ConverterTest extends FunSuite with BeforeAndAfterAll {
+ private val tsfileFolder = "../spark/src/test/resources/ConverterTest"
+ private val tsfilePath1: String = tsfileFolder + "/test_1.tsfile"
+ private val tsfilePath2: String = tsfileFolder + "/test_2.tsfile"
+ private var spark: SparkSession = _
+ private var conf: Configuration = _
+
+ override protected def beforeAll(): Unit = {
+ super.beforeAll()
+ val tsfile_folder = new File(tsfileFolder)
+ if (tsfile_folder.exists()) {
+ deleteDir(tsfile_folder)
+ }
+ tsfile_folder.mkdirs()
+ new TsFileWrite().create1(tsfilePath1)
+ new TsFileWrite().create2(tsfilePath2)
+ spark = SparkSession
+ .builder()
+ .config("spark.master", "local")
+ .appName("TSFile test")
+ .getOrCreate()
+ conf = spark.sparkContext.hadoopConfiguration
+ }
+
+ override protected def afterAll(): Unit = {
+ val folder = new File(tsfileFolder)
+ deleteDir(folder)
+ try {
+ spark.sparkContext.stop()
+ } finally {
+ super.afterAll()
+ }
+ }
+
+ def deleteDir(dir: File): Unit = {
+ if (dir.isDirectory) {
+ dir.list().foreach(f => {
+ deleteDir(new File(dir, f))
+ })
+ }
+ dir.delete()
+ }
+
+ test("getSeries") {
+ val in = new HDFSInput(new Path(new URI(tsfilePath1)), conf)
+ val reader: TsFileSequenceReader = new TsFileSequenceReader(in)
+ val tsFileMetaData = reader.readFileMetadata
+
+ val series = Converter.getSeries(tsFileMetaData)
+
+ Assert.assertEquals(6, series.size())
+ Assert.assertEquals("[device_1.sensor_3,INT32]", series.get(0).toString)
+ Assert.assertEquals("[device_1.sensor_1,FLOAT]", series.get(1).toString)
+ Assert.assertEquals("[device_1.sensor_2,INT32]", series.get(2).toString)
+ Assert.assertEquals("[device_2.sensor_3,INT32]", series.get(3).toString)
+ Assert.assertEquals("[device_2.sensor_1,FLOAT]", series.get(4).toString)
+ Assert.assertEquals("[device_2.sensor_2,INT32]", series.get(5).toString)
+
+ in.close()
+ }
+
+ test("getUnionSeries") {
+ val path1: Path = new Path(new URI(tsfilePath1))
+ val fs1: FileSystem = path1.getFileSystem(conf)
+ val status1 = fs1.getFileStatus(path1)
+
+ val path2: Path = new Path(new URI(tsfilePath2))
+ val fs2: FileSystem = path2.getFileSystem(conf)
+ val status2 = fs2.getFileStatus(path2)
+
+ val statusSeq: Seq[FileStatus] = Seq(status1, status2)
+
+ val tsfileSchema = Converter.getUnionSeries(statusSeq, conf)
+
+ Assert.assertEquals(tsfileSchema.size(), 6)
+ Assert.assertEquals("[device_1.sensor_3,INT32]", tsfileSchema.get(0).toString)
+ Assert.assertEquals("[device_1.sensor_1,FLOAT]", tsfileSchema.get(1).toString)
+ Assert.assertEquals("[device_1.sensor_2,INT32]", tsfileSchema.get(2).toString)
+ Assert.assertEquals("[device_2.sensor_3,INT32]", tsfileSchema.get(3).toString)
+ Assert.assertEquals("[device_2.sensor_1,FLOAT]", tsfileSchema.get(4).toString)
+ Assert.assertEquals("[device_2.sensor_2,INT32]", tsfileSchema.get(5).toString)
+ }
+
+ test("testToSqlValue") {
+ val boolField = new Field(TSDataType.BOOLEAN)
+ boolField.setBoolV(true)
+ val intField = new Field(TSDataType.INT32)
+ intField.setIntV(32)
+ val longField = new Field(TSDataType.INT64)
+ longField.setLongV(64l)
+ val floatField = new Field(TSDataType.FLOAT)
+ floatField.setFloatV(3.14f)
+ val doubleField = new Field(TSDataType.DOUBLE)
+ doubleField.setDoubleV(0.618d)
+ val stringField = new Field(TSDataType.TEXT)
+ stringField.setBinaryV(new Binary("pass"))
+
+ Assert.assertEquals(Converter.toSqlValue(boolField), true)
+ Assert.assertEquals(Converter.toSqlValue(intField), 32)
+ Assert.assertEquals(Converter.toSqlValue(longField), 64l)
+ Assert.assertEquals(Converter.toSqlValue(floatField), 3.14f)
+ Assert.assertEquals(Converter.toSqlValue(doubleField), 0.618d)
+ Assert.assertEquals(Converter.toSqlValue(stringField), "pass")
+ }
+
+ test("testToSparkSqlSchema") {
+ val fields: util.ArrayList[Series] = new util.ArrayList[Series]()
+ fields.add(new Series("device_1.sensor_3", TSDataType.INT32))
+ fields.add(new Series("device_1.sensor_1", TSDataType.FLOAT))
+ fields.add(new Series("device_1.sensor_2", TSDataType.INT32))
+ fields.add(new Series("device_2.sensor_3", TSDataType.INT32))
+ fields.add(new Series("device_2.sensor_1", TSDataType.FLOAT))
+ fields.add(new Series("device_2.sensor_2", TSDataType.INT32))
+
+ val sqlSchema = Converter.toSqlSchema(fields)
+
+ val expectedFields: util.ArrayList[StructField] = new util.ArrayList[StructField]()
+ expectedFields.add(StructField(QueryConstant.RESERVED_TIME, LongType, false))
+ expectedFields.add(StructField("device_1.sensor_3", IntegerType, true))
+ expectedFields.add(StructField("device_1.sensor_1", FloatType, true))
+ expectedFields.add(StructField("device_1.sensor_2", IntegerType, true))
+ expectedFields.add(StructField("device_2.sensor_3", IntegerType, true))
+ expectedFields.add(StructField("device_2.sensor_1", FloatType, true))
+ expectedFields.add(StructField("device_2.sensor_2", IntegerType, true))
+
+ Assert.assertEquals(StructType(expectedFields), sqlSchema.get)
+ }
+
+ test("prep4requiredSchema1") {
+ val in = new HDFSInput(new Path(new URI(tsfilePath1)), conf)
+ val reader: TsFileSequenceReader = new TsFileSequenceReader(in)
+ val tsFileMetaData = reader.readFileMetadata
+
+ val requiredFields: util.ArrayList[StructField] = new util.ArrayList[StructField]()
+ requiredFields.add(StructField(QueryConstant.RESERVED_TIME, LongType, false))
+ requiredFields.add(StructField("device_1.sensor_3", IntegerType, true))
+ requiredFields.add(StructField("device_1.sensor_1", FloatType, true))
+ requiredFields.add(StructField("device_1.sensor_2", IntegerType, true))
+ val requiredSchema = StructType(requiredFields)
+
+ val filteredSchema = Converter.prepSchema(requiredSchema, tsFileMetaData)
+
+ Assert.assertEquals(3, filteredSchema.size)
+ val fields = filteredSchema.fields
+ Assert.assertEquals("StructField(device_1.sensor_3,IntegerType,true)", fields(0).toString)
+ Assert.assertEquals("StructField(device_1.sensor_1,FloatType,true)", fields(1).toString)
+ Assert.assertEquals("StructField(device_1.sensor_2,IntegerType,true)", fields(2).toString)
+
+ in.close()
+ }
+
+ test("prepSchema") {
+ val in = new HDFSInput(new Path(new URI(tsfilePath1)), conf)
+ val reader: TsFileSequenceReader = new TsFileSequenceReader(in)
+ val tsFileMetaData = reader.readFileMetadata
+
+ val requiredFields: util.ArrayList[StructField] = new util.ArrayList[StructField]()
+ requiredFields.add(StructField(QueryConstant.RESERVED_TIME, LongType, false))
+ val requiredSchema = StructType(requiredFields)
+
+ val filteredSchema = Converter.prepSchema(requiredSchema, tsFileMetaData)
+
+ Assert.assertEquals(6, filteredSchema.size)
+ val fields = filteredSchema.fields
+ Assert.assertEquals("StructField(device_1.sensor_3,IntegerType,true)", fields(0).toString)
+ Assert.assertEquals("StructField(device_1.sensor_1,FloatType,true)", fields(1).toString)
+ Assert.assertEquals("StructField(device_1.sensor_2,IntegerType,true)", fields(2).toString)
+ Assert.assertEquals("StructField(device_2.sensor_3,IntegerType,true)", fields(3).toString)
+ Assert.assertEquals("StructField(device_2.sensor_1,FloatType,true)", fields(4).toString)
+ Assert.assertEquals("StructField(device_2.sensor_2,IntegerType,true)", fields(5).toString)
+
+ in.close()
+ }
+
+ test("toTsRecord") {
+ val fields: util.ArrayList[StructField] = new util.ArrayList[StructField]()
+ fields.add(StructField(QueryConstant.RESERVED_TIME, LongType, false))
+ fields.add(StructField("device_1.sensor_3", IntegerType, true))
+ fields.add(StructField("device_1.sensor_1", FloatType, true))
+ fields.add(StructField("device_1.sensor_2", IntegerType, true))
+ fields.add(StructField("device_2.sensor_3", IntegerType, true))
+ fields.add(StructField("device_2.sensor_1", FloatType, true))
+ fields.add(StructField("device_2.sensor_2", IntegerType, true))
+ val schema = StructType(fields)
+
+ var row: GenericRowWithSchema = new GenericRowWithSchema(Array(1L, null, 1.2f, 20, 19, 2.3f, 11), schema)
+ val records = Converter.toTsRecord(row)
+
+ Assert.assertEquals(2, records.size)
+ Assert.assertEquals(1, records(0).time)
+ Assert.assertEquals("device_2", records(0).deviceId)
+ val dataPoints1 = records(0).dataPointList
+ Assert.assertEquals("{measurement id: sensor_3 type: INT32 value: 19 }", dataPoints1.get(0).toString)
+ Assert.assertEquals("{measurement id: sensor_1 type: FLOAT value: 2.3 }", dataPoints1.get(1).toString)
+ Assert.assertEquals("{measurement id: sensor_2 type: INT32 value: 11 }", dataPoints1.get(2).toString)
+
+ Assert.assertEquals(1, records(1).time)
+ Assert.assertEquals("device_1", records(1).deviceId)
+ val dataPoints2 = records(1).dataPointList
+ Assert.assertEquals("{measurement id: sensor_1 type: FLOAT value: 1.2 }", dataPoints2.get(0).toString)
+ Assert.assertEquals("{measurement id: sensor_2 type: INT32 value: 20 }", dataPoints2.get(1).toString)
+ }
+
+ test("toQueryExpression") {
+ val fields: util.ArrayList[StructField] = new util.ArrayList[StructField]()
+ fields.add(StructField(QueryConstant.RESERVED_TIME, LongType, false))
+ fields.add(StructField("device_1.sensor_1", FloatType, true))
+ fields.add(StructField("device_1.sensor_2", IntegerType, true))
+ val schema = StructType(fields)
+
+ val ft1 = IsNotNull("time")
+ val ft2 = GreaterThan("device_1.sensor_1", 0.0f)
+ val ft3 = LessThan("device_1.sensor_2", 22)
+ val ft2_3 = Or(ft2, ft3)
+ val ft4 = LessThan("time", 4L)
+ val filters: Seq[Filter] = Seq(ft1, ft2_3, ft4)
+
+ val expression = Converter.toQueryExpression(schema, filters)
+
+ Assert.assertEquals(true, expression.hasQueryFilter)
+ Assert.assertEquals(2, expression.getSelectedSeries.size())
+ Assert.assertEquals("device_1.sensor_1", expression.getSelectedSeries.get(0).toString)
+ Assert.assertEquals("device_1.sensor_2", expression.getSelectedSeries.get(1).toString)
+ Assert.assertEquals("[[[device_1.sensor_1:value > 0.0] || [device_1.sensor_2:value < 22]] && [time < 4]]", expression.getExpression.toString)
+ }
+}
diff --git a/spark/src/test/scala/org/apache/iotdb/tsfile/HDFSInputTest.java b/spark/src/test/scala/org/apache/iotdb/tsfile/HDFSInputTest.java
new file mode 100644
index 0000000..94f8b0a
--- /dev/null
+++ b/spark/src/test/scala/org/apache/iotdb/tsfile/HDFSInputTest.java
@@ -0,0 +1,79 @@
+/**
+ * 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.iotdb.tsfile;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import org.apache.iotdb.tsfile.io.HDFSInput;
+import org.apache.iotdb.tool.TsFileWrite;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class HDFSInputTest {
+
+ private String folder = "../spark/src/test/resources/HDFSInputTest";
+ private String path = folder + "/test.tsfile";
+ private HDFSInput in;
+
+ @Before
+ public void before() throws Exception {
+ File tsfile_folder = new File(folder);
+ if (tsfile_folder.exists()) {
+ deleteDir(tsfile_folder);
+ }
+ tsfile_folder.mkdirs();
+ TsFileWrite tsFileWrite = new TsFileWrite();
+ tsFileWrite.create1(path);
+ in = new HDFSInput(path);
+ }
+
+ @After
+ public void after() throws IOException {
+ in.close();
+ File tsfile_folder = new File(folder);
+ deleteDir(tsfile_folder);
+ }
+
+ private void deleteDir(File dir) {
+ if (dir.isDirectory()) {
+ for (File f : dir.listFiles()) {
+ deleteDir(f);
+ }
+ }
+ dir.delete();
+ }
+
+ @Test
+ public void test_read1() throws IOException {
+ int size = 2000;
+ ByteBuffer buffer = ByteBuffer.allocate(size);
+ Assert.assertEquals(size, in.read(buffer));
+ }
+
+ @Test
+ public void test_read2() throws IOException {
+ int size = 2000;
+ long pos = 20L;
+ ByteBuffer buffer = ByteBuffer.allocate(size);
+ Assert.assertEquals(size, in.read(buffer, pos));
+ }
+}
diff --git a/spark/src/test/scala/org/apache/iotdb/tsfile/TSFileSuit.scala b/spark/src/test/scala/org/apache/iotdb/tsfile/TSFileSuit.scala
new file mode 100644
index 0000000..48d428c
--- /dev/null
+++ b/spark/src/test/scala/org/apache/iotdb/tsfile/TSFileSuit.scala
@@ -0,0 +1,217 @@
+/**
+ * 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.iotdb.tsfile
+
+import java.io.File
+
+import org.apache.iotdb.tsfile.common.constant.QueryConstant
+import org.apache.iotdb.tool.TsFileWrite
+import org.apache.spark.sql.SparkSession
+import org.apache.spark.sql.types._
+import org.junit.Assert
+import org.scalatest.{BeforeAndAfterAll, FunSuite}
+
+
+class TSFileSuit extends FunSuite with BeforeAndAfterAll {
+
+ private val resourcesFolder = "../spark/src/test/resources"
+ private val tsfileFolder1 = resourcesFolder + "/tsfile1"
+ private val tsfileFolder2 = resourcesFolder + "/tsfile2"
+ private val tsfile1 = tsfileFolder1 + "/test1.tsfile"
+ private val tsfile2 = tsfileFolder1 + "/test2.tsfile"
+ private val tsfile3 = tsfileFolder2 + "/test.tsfile"
+ private val outputPath = "../spark/src/test/resources/output"
+ private val outputPathFile = outputPath + "/part-m-00000"
+ private val outputPath2 = "../spark/src/test/resources/output2"
+ private val outputPathFile2 = outputPath2 + "/part-m-00000"
+ private val outputHDFSPath = "hdfs://localhost:9000/usr/hadoop/output"
+ private val outputHDFSPathFile = outputHDFSPath + "/part-m-00000"
+ private var spark: SparkSession = _
+
+ override protected def beforeAll(): Unit = {
+ super.beforeAll()
+
+ val resources = new File(resourcesFolder)
+ if (!resources.exists())
+ resources.mkdirs()
+
+ val tsfile_folder1 = new File(tsfileFolder1)
+ if (tsfile_folder1.exists()) {
+ deleteDir(tsfile_folder1)
+ }
+ tsfile_folder1.mkdirs()
+
+ val tsfile_folder2 = new File(tsfileFolder2)
+ if (tsfile_folder2.exists()) {
+ deleteDir(tsfile_folder2)
+ }
+ tsfile_folder2.mkdirs()
+
+ new TsFileWrite().create1(tsfile1)
+ new TsFileWrite().create2(tsfile2)
+ new TsFileWrite().create3(tsfile3)
+
+ val output = new File(outputPath)
+ if (output.exists())
+ deleteDir(output)
+ val output2 = new File(outputPath2)
+ if (output2.exists())
+ deleteDir(output2)
+
+ spark = SparkSession
+ .builder()
+ .config("spark.master", "local")
+ .appName("TSFile test")
+ .getOrCreate()
+ }
+
+ override protected def afterAll(): Unit = {
+ val folder1 = new File(tsfileFolder1)
+ deleteDir(folder1)
+ val folder2 = new File(tsfileFolder2)
+ deleteDir(folder2)
+ val out = new File(outputPath)
+ deleteDir(out)
+ val out2 = new File(outputPath2)
+ deleteDir(out2)
+ try {
+ spark.sparkContext.stop()
+ } finally {
+ super.afterAll()
+ }
+ }
+
+ def deleteDir(dir: File): Unit = {
+ if (dir.isDirectory) {
+ dir.list().foreach(f => {
+ deleteDir(new File(dir, f))
+ })
+ }
+ dir.delete()
+ }
+
+ test("test write 1") {
+ val df = spark.read.tsfile(tsfile1)
+ df.write.tsfile(outputPath)
+ val newDf = spark.read.tsfile(outputPathFile)
+ Assert.assertEquals(newDf.collectAsList(), df.collectAsList())
+ }
+
+ test("test write 2") {
+ val df = spark.read.tsfile(tsfile2)
+ df.write.tsfile(outputPath2)
+ val newDf = spark.read.tsfile(outputPathFile2)
+ Assert.assertEquals(newDf.collectAsList(), df.collectAsList())
+ }
+
+ test("testSelect * from tsfile1") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table")
+ val count = newDf.count()
+ Assert.assertEquals(7, count)
+ }
+
+ test("testSelect * from tsfile2") {
+ val df = spark.read.tsfile(tsfile2)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table")
+ val count = newDf.count()
+ Assert.assertEquals(TsFileWrite.largeNum, count)
+ }
+
+ test("testCount") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select count(*) from tsfile_table")
+ Assert.assertEquals(7, newDf.head().apply(0).asInstanceOf[Long])
+ }
+
+ test("testSelect time") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select time from tsfile_table")
+ Assert.assertEquals(7, newDf.count())
+ }
+
+ test("testSelectString") {
+ val df = spark.read.tsfile(tsfile3)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_2` = \"Monday\"")
+ Assert.assertEquals(1, newDf.count())
+ }
+
+ test("testSelectBoolean") {
+ val df = spark.read.tsfile(tsfile3)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1` = true")
+ Assert.assertEquals(2, newDf.count())
+ }
+
+ test("testSelectWithFilterAnd") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1`>0 and `device_1.sensor_2` < 22")
+ Assert.assertEquals(5, newDf.count())
+ }
+
+ test("testSelectWithFilterOr") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1`>0 or `device_1.sensor_2` < 22")
+ Assert.assertEquals(7, newDf.count())
+ }
+
+ test("testSelectComplex") {
+ val df = spark.read.tsfile(tsfile1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where (`device_1.sensor_1`>0 or `device_1.sensor_2` < 22) and time < 4")
+ Assert.assertEquals(3, newDf.count())
+ }
+
+ test("testMultiFiles") {
+ val df = spark.read.tsfile(tsfileFolder1)
+ df.createOrReplaceTempView("tsfile_table")
+ Assert.assertEquals(TsFileWrite.largeNum + 7, df.count())
+ }
+
+ test("testMultiFilesWithFilter1") {
+ val df = spark.read.tsfile(tsfileFolder1)
+ df.createOrReplaceTempView("tsfile_table")
+ val newDf = spark.sql("select * from tsfile_table where `device_1.sensor_1` >0 " +
+ "and `device_1.sensor_1` <10 or `device_1.sensor_2` >0")
+ Assert.assertEquals(16, newDf.count())
+ }
+
+ test("testQuerySchema") {
+ val df = spark.read.format("org.apache.iotdb.tsfile").load(tsfile1)
+
+ val expected = StructType(Seq(
+ StructField(QueryConstant.RESERVED_TIME, LongType, nullable = true),
+ StructField("device_1.sensor_3", IntegerType, nullable = true),
+ StructField("device_1.sensor_1", FloatType, nullable = true),
+ StructField("device_1.sensor_2", IntegerType, nullable = true),
+ StructField("device_2.sensor_3", IntegerType, nullable = true),
+ StructField("device_2.sensor_1", FloatType, nullable = true),
+ StructField("device_2.sensor_2", IntegerType, nullable = true)
+ ))
+ Assert.assertEquals(expected, df.schema)
+ }
+
+}
\ No newline at end of file
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/common/constant/QueryConstant.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/common/constant/QueryConstant.java
index bf3622a..1b83c7f 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/common/constant/QueryConstant.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/common/constant/QueryConstant.java
@@ -25,5 +25,13 @@ public class QueryConstant {
// The end offset for the partition
public static final String PARTITION_END_OFFSET = "partition_end_offset";
+ public static final String RESERVED_TIME = "time";
+
+ public static final String INT32 = "INT32";
+ public static final String INT64 = "INT64";
+ public static final String FLOAT = "FLOAT";
+ public static final String DOUBLE = "DOUBLE";
+ public static final String BYTE_ARRAY = "BYTE_ARRAY";
+
private QueryConstant(){}
}
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/TsFileSequenceReader.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/TsFileSequenceReader.java
index 0f6c2ed..9f7ab47 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/TsFileSequenceReader.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/TsFileSequenceReader.java
@@ -85,7 +85,7 @@ public class TsFileSequenceReader implements AutoCloseable{
tsFileInput = new DefaultTsFileInput(path);
try {
if (loadMetadataSize) {
- loadMetadataSize();
+ loadMetadataSize();
}
} catch (Throwable e) {
tsFileInput.close();
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/common/TimeRange.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/common/TimeRange.java
new file mode 100644
index 0000000..cdff289
--- /dev/null
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/common/TimeRange.java
@@ -0,0 +1,289 @@
+/**
+ * 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.iotdb.tsfile.read.common;
+
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.iotdb.tsfile.read.expression.IExpression;
+import org.apache.iotdb.tsfile.read.expression.impl.BinaryExpression;
+import org.apache.iotdb.tsfile.read.expression.impl.GlobalTimeExpression;
+import org.apache.iotdb.tsfile.read.filter.TimeFilter;
+
+/**
+ * interval [min,max] of long data type
+ *
+ * Reference: http://www.java2s.com/Code/Java/Collections-Data-Structure/Anumericalinterval.htm
+ *
+ * @author ryanm
+ */
+public class TimeRange implements Comparable<TimeRange> {
+
+ /**
+ * The lower value
+ */
+ private long min = 0;
+
+ /**
+ * The upper value
+ */
+ private long max = 0;
+
+ /**
+ * Initialize a closed interval [min,max].
+ * @param min the left endpoint of the closed interval
+ * @param max the right endpoint of the closed interval
+ */
+ public TimeRange(long min, long max) {
+ set(min, max);
+ }
+
+ @Override
+ public int compareTo(TimeRange r) {
+ if (r == null) {
+ throw new NullPointerException("The input cannot be null!");
+ }
+ long res1 = this.min - r.min;
+ if (res1 > 0) {
+ return 1;
+ } else if (res1 < 0) {
+ return -1;
+ } else {
+ long res2 = this.max - r.max;
+ if (res2 > 0) {
+ return 1;
+ } else if (res2 < 0) {
+ return -1;
+ } else {
+ return 0;
+ }
+ }
+ }
+
+ /**
+ * @return true if the value lies between the min and max values, inclusively
+ */
+ public boolean contains(long value) {
+ return min <= value && max >= value;
+ }
+
+ /**
+ * @return true if the given range lies in this range, inclusively
+ */
+ public boolean contains(TimeRange r) {
+ return min <= r.min && max >= r.max;
+ }
+
+ /**
+ * @param min
+ * @param max
+ */
+ public void set(long min, long max) {
+ this.min = min;
+ this.max = max;
+
+ sort();
+ }
+
+ /**
+ * @param r
+ */
+ public void set(TimeRange r) {
+ set(r.getMin(), r.getMax());
+ }
+
+ /**
+ * @return The lower range boundary
+ */
+ public long getMin() {
+ return min;
+ }
+
+ /**
+ * @param min
+ */
+ public void setMin(long min) {
+ this.min = min;
+
+ sort();
+ }
+
+ /**
+ * @return The upper range boundary
+ */
+ public long getMax() {
+ return max;
+ }
+
+ /**
+ * @param max
+ */
+ public void setMax(long max) {
+ this.max = max;
+
+ sort();
+ }
+
+ private void sort() {
+ if (min > max) {
+ long t = min;
+ min = max;
+ max = t;
+ }
+ }
+
+ /**
+ * @return <code>true</code> if the intersection exists
+ */
+ public boolean intersection(TimeRange r, TimeRange dest) {
+ if (intersects(r)) {
+ dest.set(Math.max(min, r.min), Math.min(max, r.max));
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * @return <code>true</code> if the ranges have values in common
+ */
+ public boolean intersects(TimeRange r) {
+ return overlaps(min, max, r.min, r.max);
+ }
+
+ /**
+ * @return <code>true</code> if the ranges overlap
+ */
+ public static boolean overlaps(long minA, long maxA, long minB, long maxB) {
+ if (minA > maxA) {
+ throw new IllegalArgumentException("Invalid input: minA should not be larger than maxA.");
+ }
+ if (minB > maxB) {
+ throw new IllegalArgumentException("Invalid input: minB should not be larger than maxB.");
+ }
+
+ // Because timestamp is long data type, x and x+1 are considered continuous.
+ return !(minA >= maxB + 2 || maxA <= minB - 2);
+ }
+
+ @Override
+ public String toString() {
+ return "[ " + min + " : " + max + " ]";
+ }
+
+ // NOTE the primitive timeRange is always a closed interval [min,max] and
+ // only in getRemains functions are leftClose and rightClose considered.
+ private boolean leftClose = true; // default true
+ private boolean rightClose = true; // default true
+
+ public void setLeftClose(boolean leftClose) {
+ this.leftClose = leftClose;
+ }
+
+ public void setRightClose(boolean rightClose) {
+ this.rightClose = rightClose;
+ }
+
+ public boolean getLeftClose() {
+ return leftClose;
+ }
+
+ public boolean getRightClose() {
+ return rightClose;
+ }
+
+ /**
+ * Get the remaining time ranges in the current ranges but not in timeRangesPrev.
+ *
+ * NOTE the primitive timeRange is always a closed interval [min,max] and only in this function
+ * are leftClose and rightClose changed.
+ *
+ * @param timeRangesPrev time ranges union in ascending order
+ * @return the remaining time ranges
+ */
+ public List<TimeRange> getRemains(ArrayList<TimeRange> timeRangesPrev) {
+ List<TimeRange> remains = new ArrayList<>();
+
+ for (TimeRange prev : timeRangesPrev) {
+ if (prev.min >= max + 2) { // keep consistent with the definition of `overlap`
+ break; // break early since timeRangesPrev is sorted
+ }
+
+ if (intersects(prev)) {
+ if (prev.contains(this)) {
+ return remains;
+ } else if (this.contains(prev)) {
+ if (prev.min > this.min && prev.max == this.max) {
+ TimeRange r = new TimeRange(this.min, prev.min);
+ r.setLeftClose(this.leftClose);
+ r.setRightClose(false);
+ remains.add(r);
+ return remains; // because timeRangesPrev is sorted
+ } else if (prev.min == this.min) { // && prev.max < this.max
+ min = prev.max;
+ leftClose = false;
+ } else {
+ TimeRange r = new TimeRange(this.min, prev.min);
+ r.setLeftClose(this.leftClose);
+ r.setRightClose(false);
+ remains.add(r);
+
+ min = prev.max;
+ leftClose = false;
+ }
+ } else { // intersect without one containing the other
+ if (prev.min < this.min) {
+ min = prev.max;
+ leftClose = false;
+ } else {
+ TimeRange r = new TimeRange(this.min, prev.min);
+ r.setLeftClose(this.leftClose);
+ r.setRightClose(false);
+ remains.add(r);
+ return remains;
+ }
+ }
+ }
+ }
+
+ TimeRange r = new TimeRange(this.min, this.max);
+ r.setLeftClose(this.leftClose);
+ r.setRightClose(this.rightClose);
+ remains.add(r);
+
+ return remains;
+ }
+
+ public IExpression getExpression() {
+ IExpression left;
+ IExpression right;
+ if (leftClose) {
+ left = new GlobalTimeExpression(TimeFilter.gtEq(min));
+ } else {
+ left = new GlobalTimeExpression(TimeFilter.gt(min));
+ }
+
+ if (rightClose) {
+ right = new GlobalTimeExpression(TimeFilter.ltEq(max));
+ } else {
+ right = new GlobalTimeExpression(TimeFilter.lt(max));
+ }
+
+ return BinaryExpression.and(left, right);
+ }
+}
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerier.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerier.java
index 6737896..1a0e17a 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerier.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerier.java
@@ -19,17 +19,22 @@
package org.apache.iotdb.tsfile.read.controller;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import org.apache.iotdb.tsfile.exception.write.NoMeasurementException;
import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.iotdb.tsfile.read.common.TimeRange;
public interface MetadataQuerier {
List<ChunkMetaData> getChunkMetaDataList(Path path) throws IOException;
+ Map<Path, List<ChunkMetaData>> getChunkMetaDataMap(List<Path> paths) throws IOException;
+
TsFileMetaData getWholeFileMetadata();
/**
@@ -47,4 +52,39 @@ public interface MetadataQuerier {
* @throws NoMeasurementException if the measurement not exists.
*/
TSDataType getDataType(String measurement) throws NoMeasurementException;
+
+ /**
+ * get time ranges of chunkGroups in or before the current partition and return the union result in ascending order
+ *
+ * @param paths timeseries paths
+ * @param targetMode InPartition or PrevPartition
+ * @return time ranges union in ascending order
+ * @throws IOException
+ */
+ public ArrayList<TimeRange> getTimeRangeInOrPrev(List<Path> paths, LoadMode targetMode)
+ throws IOException;
+
+ /**
+ * get the load mode of the MetadataQuerier
+ *
+ * @return LoadMode enum
+ */
+ LoadMode getLoadMode();
+
+ /**
+ * set the load mode of the MetadataQuerier
+ *
+ * @param mode enum
+ */
+ void setLoadMode(LoadMode mode);
+
+ /**
+ * The load mode of the MetadataQuerier:
+ * NoPartition - load metadata of all chunkgroups in the file
+ * InPartition - load metadata of chunkgroups which fall in the current partition
+ * PrevPartition - load metadata of chunkgroups which fall ahead the current partition
+ */
+ enum LoadMode {
+ NoPartition, InPartition, PrevPartition
+ }
}
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImpl.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImpl.java
index acc8fc4..9f496be 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImpl.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImpl.java
@@ -20,8 +20,10 @@ package org.apache.iotdb.tsfile.read.controller;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -37,6 +39,7 @@ import org.apache.iotdb.tsfile.file.metadata.TsFileMetaData;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.iotdb.tsfile.read.common.TimeRange;
import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
public class MetadataQuerierByFileImpl implements MetadataQuerier {
@@ -49,9 +52,18 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
private TsFileSequenceReader tsFileReader;
- private boolean partitionMode = false;
- private long partitionStartOffset;
- private long partitionEndOffset;
+ private LoadMode mode;
+
+ private long partitionStartOffset = 0L;
+ private long partitionEndOffset = 0L;
+
+ public LoadMode getLoadMode() {
+ return mode;
+ }
+
+ public void setLoadMode(LoadMode mode) {
+ this.mode = mode;
+ }
/**
* Constructor of MetadataQuerierByFileImpl.
@@ -59,7 +71,7 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
public MetadataQuerierByFileImpl(TsFileSequenceReader tsFileReader) throws IOException {
this.tsFileReader = tsFileReader;
this.fileMetaData = tsFileReader.readFileMetadata();
- this.partitionMode = false;
+ this.mode = LoadMode.NoPartition;
chunkMetaDataCache = new LRUCache<Path, List<ChunkMetaData>>(CHUNK_METADATA_CACHE_SIZE) {
@Override
public List<ChunkMetaData> loadObjectByKey(Path key) throws IOException {
@@ -81,7 +93,7 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
throw new IllegalArgumentException(
"Input parameters miss partition_start_offset or partition_end_offset");
}
- this.partitionMode = true;
+ this.mode = LoadMode.InPartition;
this.partitionStartOffset = params.get(QueryConstant.PARTITION_START_OFFSET);
this.partitionEndOffset = params.get(QueryConstant.PARTITION_END_OFFSET);
chunkMetaDataCache = new LRUCache<Path, List<ChunkMetaData>>(CHUNK_METADATA_CACHE_SIZE) {
@@ -98,6 +110,18 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
}
@Override
+ public Map<Path, List<ChunkMetaData>> getChunkMetaDataMap(List<Path> paths) throws IOException {
+ Map<Path, List<ChunkMetaData>> chunkMetaDatas = new HashMap<>();
+ for (Path path : paths) {
+ if (!chunkMetaDatas.containsKey(path)) {
+ chunkMetaDatas.put(path, new ArrayList<>());
+ }
+ chunkMetaDatas.get(path).addAll(getChunkMetaDataList(path));
+ }
+ return chunkMetaDatas;
+ }
+
+ @Override
public TsFileMetaData getWholeFileMetadata() {
return fileMetaData;
}
@@ -137,7 +161,7 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
// d1
for (ChunkGroupMetaData chunkGroupMetaData : tsDeviceMetadata
- .getChunkGroupMetaDataList()) { // TODO make this function
+ .getChunkGroupMetaDataList()) {
// better
if (enough) {
@@ -182,9 +206,9 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
}
@Override
- public TSDataType getDataType(String measurement) throws NoMeasurementException {
+ public TSDataType getDataType(String measurement) throws NoMeasurementException {
MeasurementSchema measurementSchema = fileMetaData.getMeasurementSchema().get(measurement);
- if(measurementSchema != null) {
+ if (measurementSchema != null) {
return measurementSchema.getType();
}
throw new NoMeasurementException(String.format("%s not found.", measurement));
@@ -205,34 +229,90 @@ public class MetadataQuerierByFileImpl implements MetadataQuerier {
// get all ChunkMetaData of this path included in all ChunkGroups of this device
List<ChunkMetaData> chunkMetaDataList = new ArrayList<>();
for (ChunkGroupMetaData chunkGroupMetaData : tsDeviceMetadata.getChunkGroupMetaDataList()) {
- if (!checkAccess(chunkGroupMetaData)) {
- continue;
- }
- List<ChunkMetaData> chunkMetaDataListInOneChunkGroup = chunkGroupMetaData
- .getChunkMetaDataList();
- for (ChunkMetaData chunkMetaData : chunkMetaDataListInOneChunkGroup) {
- if (path.getMeasurement().equals(chunkMetaData.getMeasurementUid())) {
- chunkMetaData.setVersion(chunkGroupMetaData.getVersion());
- chunkMetaDataList.add(chunkMetaData);
+ if (checkAccess(chunkGroupMetaData)) {
+ List<ChunkMetaData> chunkMetaDataListInOneChunkGroup = chunkGroupMetaData
+ .getChunkMetaDataList();
+ for (ChunkMetaData chunkMetaData : chunkMetaDataListInOneChunkGroup) {
+ if (path.getMeasurement().equals(chunkMetaData.getMeasurementUid())) {
+ chunkMetaData.setVersion(chunkGroupMetaData.getVersion());
+ chunkMetaDataList.add(chunkMetaData);
+ }
}
}
}
return chunkMetaDataList;
}
- private boolean checkAccess(ChunkGroupMetaData chunkGroupMetaData) {
- if (!partitionMode) {
- return true; // always true
+ public ArrayList<TimeRange> getTimeRangeInOrPrev(List<Path> paths, LoadMode targetMode)
+ throws IOException {
+ if (mode == LoadMode.NoPartition) {
+ throw new IOException(
+ "Wrong use of getTimeRangeInOrPrev: should not be in NoPartition mode");
+ }
+
+ // change the mode temporarily to control loadChunkMetadata's checkAccess function
+ this.mode = targetMode;
+
+ ArrayList<TimeRange> unionCandidates = new ArrayList<>();
+ for (Path path : paths) {
+ List<ChunkMetaData> chunkMetaDataList = loadChunkMetadata(path);
+ for (ChunkMetaData chunkMetaData : chunkMetaDataList) {
+ unionCandidates
+ .add(new TimeRange(chunkMetaData.getStartTime(), chunkMetaData.getEndTime()));
+ }
+ }
+ Collections.sort(unionCandidates);
+
+ // union
+ ArrayList<TimeRange> unionResult = new ArrayList<>();
+ Iterator<TimeRange> iterator = unionCandidates.iterator();
+ TimeRange range_curr = null;
+
+ if (!iterator.hasNext()) {
+ return unionResult;
+ } else {
+ TimeRange r = iterator.next();
+ range_curr = new TimeRange(r.getMin(), r.getMax());
+ }
+
+ while (iterator.hasNext()) {
+ TimeRange range_next = iterator.next();
+ if (range_curr.intersects(range_next)) {
+ range_curr.set(Math.min(range_curr.getMin(), range_next.getMin()),
+ Math.max(range_curr.getMax(), range_next.getMax()));
+ } else {
+ unionResult.add(new TimeRange(range_curr.getMin(), range_curr.getMax()));
+ range_curr.set(range_next.getMin(), range_next.getMax());
+ }
}
+ unionResult.add(new TimeRange(range_curr.getMin(), range_curr.getMax()));
+
+ this.mode = LoadMode.InPartition; // restore the mode to InPartition
+ return unionResult;
+
+ }
+
+ /**
+ * check if the given chunk group can be accessed under the current load mode
+ * @param chunkGroupMetaData a chunk group's metadata
+ * @return True if the chunk group can be accessed. False otherwise.
+ * @throws IOException illegal mode
+ */
+ private boolean checkAccess(ChunkGroupMetaData chunkGroupMetaData) throws IOException {
long startOffsetOfChunkGroup = chunkGroupMetaData.getStartOffsetOfChunkGroup();
long endOffsetOfChunkGroup = chunkGroupMetaData.getEndOffsetOfChunkGroup();
long middleOffsetOfChunkGroup = (startOffsetOfChunkGroup + endOffsetOfChunkGroup) / 2;
- if (partitionStartOffset < middleOffsetOfChunkGroup
- && middleOffsetOfChunkGroup <= partitionEndOffset) {
- return true;
- } else {
- return false;
+ switch (mode) {
+ case NoPartition:
+ return true; // always true
+ case InPartition:
+ return (partitionStartOffset <= middleOffsetOfChunkGroup
+ && middleOffsetOfChunkGroup < partitionEndOffset);
+ case PrevPartition:
+ return (middleOffsetOfChunkGroup < partitionStartOffset);
+ default:
+ throw new IOException(
+ "unexpected mode! It should be one of {NoPartition, InPartition, BeforePartition}");
}
}
-
}
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/ExecutorWithTimeGenerator.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/ExecutorWithTimeGenerator.java
index 96c29ad..6114ce6 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/ExecutorWithTimeGenerator.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/ExecutorWithTimeGenerator.java
@@ -21,6 +21,7 @@ package org.apache.iotdb.tsfile.read.query.executor;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
@@ -67,20 +68,26 @@ public class ExecutorWithTimeGenerator implements QueryExecutor {
List<SeriesReaderByTimestamp> readersOfSelectedSeries = new ArrayList<>();
List<TSDataType> dataTypes = new ArrayList<>();
- for (int i = 0; i < cached.size(); i++) {
-
- List<ChunkMetaData> chunkMetaDataList = metadataQuerier
- .getChunkMetaDataList(selectedPathList.get(i));
- dataTypes.add(chunkMetaDataList.get(0).getTsDataType());
-
- if (cached.get(i)) {
- readersOfSelectedSeries.add(null);
- continue;
+ Iterator<Boolean> cachedIterator = cached.iterator();
+ Iterator<Path> selectedPathIterator = selectedPathList.iterator();
+ while (cachedIterator.hasNext()) {
+ boolean cachedValue = cachedIterator.next();
+ Path selectedPath = selectedPathIterator.next();
+
+ List<ChunkMetaData> chunkMetaDataList = metadataQuerier.getChunkMetaDataList(selectedPath);
+ if (chunkMetaDataList.size() != 0) {
+ dataTypes.add(chunkMetaDataList.get(0).getTsDataType());
+ if (cachedValue) {
+ readersOfSelectedSeries.add(null);
+ continue;
+ }
+ SeriesReaderByTimestamp seriesReader = new SeriesReaderByTimestamp(chunkLoader,
+ chunkMetaDataList);
+ readersOfSelectedSeries.add(seriesReader);
+ } else {
+ selectedPathIterator.remove();
+ cachedIterator.remove();
}
-
- SeriesReaderByTimestamp seriesReader = new SeriesReaderByTimestamp(chunkLoader,
- chunkMetaDataList);
- readersOfSelectedSeries.add(seriesReader);
}
return new DataSetWithTimeGenerator(selectedPathList, cached, dataTypes, timeGenerator,
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/TsFileExecutor.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/TsFileExecutor.java
index 39883af..1e18792 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/TsFileExecutor.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/read/query/executor/TsFileExecutor.java
@@ -26,10 +26,13 @@ import org.apache.iotdb.tsfile.exception.write.NoMeasurementException;
import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.iotdb.tsfile.read.common.TimeRange;
import org.apache.iotdb.tsfile.read.controller.ChunkLoader;
import org.apache.iotdb.tsfile.read.controller.MetadataQuerier;
+import org.apache.iotdb.tsfile.read.controller.MetadataQuerier.LoadMode;
import org.apache.iotdb.tsfile.read.expression.IExpression;
import org.apache.iotdb.tsfile.read.expression.QueryExpression;
+import org.apache.iotdb.tsfile.read.expression.impl.BinaryExpression;
import org.apache.iotdb.tsfile.read.expression.impl.GlobalTimeExpression;
import org.apache.iotdb.tsfile.read.expression.util.ExpressionOptimizer;
import org.apache.iotdb.tsfile.read.query.dataset.DataSetWithoutTimeGenerator;
@@ -51,8 +54,61 @@ public class TsFileExecutor implements QueryExecutor {
@Override
public QueryDataSet execute(QueryExpression queryExpression) throws IOException {
+ LoadMode mode = metadataQuerier.getLoadMode();
+ if (mode == LoadMode.PrevPartition) {
+ throw new IOException("Wrong use of PrevPartition mode.");
+ }
+
+ if (metadataQuerier.getLoadMode() == LoadMode.InPartition) {
+ // (1) get the sorted union covered time ranges of chunkGroups in the current partition
+ ArrayList<TimeRange> timeRangesIn = metadataQuerier
+ .getTimeRangeInOrPrev(queryExpression.getSelectedSeries(), LoadMode.InPartition);
- metadataQuerier.loadChunkMetaDatas(queryExpression.getSelectedSeries());
+ // (2) check if null
+ if (timeRangesIn.size() == 0) {
+ return new DataSetWithoutTimeGenerator(new ArrayList<Path>(), new ArrayList<TSDataType>(),
+ new ArrayList<FileSeriesReader>()); // return empty QueryDataSet
+ }
+
+ // (3) get the sorted union covered time ranges of chunkGroups before the current partition
+ ArrayList<TimeRange> timeRangesPrev = metadataQuerier
+ .getTimeRangeInOrPrev(queryExpression.getSelectedSeries(), LoadMode.PrevPartition);
+
+ // (4) calculate the remaining time range
+ ArrayList<TimeRange> timeRangesRemains = new ArrayList<>();
+ for (TimeRange in : timeRangesIn) {
+ ArrayList<TimeRange> remains = new ArrayList<>(in.getRemains(timeRangesPrev));
+ timeRangesRemains.addAll(remains);
+ }
+
+ // (5) check if null
+ if (timeRangesRemains.size() == 0) {
+ return new DataSetWithoutTimeGenerator(new ArrayList<Path>(), new ArrayList<TSDataType>(),
+ new ArrayList<FileSeriesReader>()); // return empty QueryDataSet
+ }
+
+ // (6) add an additional global time filter based on the remaining time range
+ IExpression timeBound = timeRangesRemains.get(0).getExpression();
+ for (int i = 1; i < timeRangesRemains.size(); i++) {
+ timeBound = BinaryExpression
+ .or(timeBound, timeRangesRemains.get(i).getExpression());
+ }
+
+ if (queryExpression.hasQueryFilter()) {
+ IExpression timeBoundExpression = BinaryExpression
+ .and(queryExpression.getExpression(), timeBound);
+ queryExpression.setExpression(timeBoundExpression);
+ } else {
+ queryExpression.setExpression(timeBound);
+ }
+
+ // (7) with global time filters, we can now remove partition constraints
+ metadataQuerier.setLoadMode(LoadMode.NoPartition);
+ metadataQuerier.loadChunkMetaDatas(queryExpression.getSelectedSeries());
+
+ } else { // NoPartition mode
+ metadataQuerier.loadChunkMetaDatas(queryExpression.getSelectedSeries());
+ }
if (queryExpression.hasQueryFilter()) {
try {
@@ -104,14 +160,12 @@ public class TsFileExecutor implements QueryExecutor {
}
/**
- *
* @param selectedPathList completed path
* @param timeFilter a GlobalTimeExpression or null
* @return DataSetWithoutTimeGenerator
- * @throws IOException
- * @throws NoMeasurementException
*/
- private QueryDataSet executeMayAttachTimeFiler(List<Path> selectedPathList, GlobalTimeExpression timeFilter)
+ private QueryDataSet executeMayAttachTimeFiler(List<Path> selectedPathList,
+ GlobalTimeExpression timeFilter)
throws IOException, NoMeasurementException {
List<FileSeriesReader> readersOfSelectedSeries = new ArrayList<>();
List<TSDataType> dataTypes = new ArrayList<>();
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/write/TsFileWriter.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/write/TsFileWriter.java
index e784023..b201324 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/write/TsFileWriter.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/write/TsFileWriter.java
@@ -37,6 +37,7 @@ import org.apache.iotdb.tsfile.write.schema.FileSchema;
import org.apache.iotdb.tsfile.write.schema.JsonConverter;
import org.apache.iotdb.tsfile.write.schema.MeasurementSchema;
import org.apache.iotdb.tsfile.write.writer.TsFileIOWriter;
+import org.apache.iotdb.tsfile.write.writer.TsFileOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -110,6 +111,17 @@ public class TsFileWriter implements AutoCloseable{
/**
* init this TsFileWriter.
*
+ * @param output the TsFileOutput of the file to be written by this TsFileWriter
+ * @param schema the schema of this TsFile
+ * @throws IOException
+ */
+ public TsFileWriter(TsFileOutput output, FileSchema schema) throws IOException {
+ this(new TsFileIOWriter(output), schema, TSFileDescriptor.getInstance().getConfig());
+ }
+
+ /**
+ * init this TsFileWriter.
+ *
* @param file the File to be written by this TsFileWriter
* @param conf the configuration of this TsFile
*/
diff --git a/tsfile/src/main/java/org/apache/iotdb/tsfile/write/writer/TsFileIOWriter.java b/tsfile/src/main/java/org/apache/iotdb/tsfile/write/writer/TsFileIOWriter.java
index 5d0a2a7..c83c8e8 100644
--- a/tsfile/src/main/java/org/apache/iotdb/tsfile/write/writer/TsFileIOWriter.java
+++ b/tsfile/src/main/java/org/apache/iotdb/tsfile/write/writer/TsFileIOWriter.java
@@ -89,6 +89,17 @@ public class TsFileIOWriter {
}
/**
+ * for writing a new tsfile.
+ *
+ * @param output be used to output written data
+ * @throws IOException
+ */
+ public TsFileIOWriter(TsFileOutput output) throws IOException {
+ this.out = output;
+ startFile();
+ }
+
+ /**
* for writing data into an existing and incomplete Tsfile. The caller need to guarantee existing
* data in the TsFileOutput matches the given metadata list
*
diff --git a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadInPartitionTest.java b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadInPartitionTest.java
new file mode 100644
index 0000000..96bf3c1
--- /dev/null
+++ b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadInPartitionTest.java
@@ -0,0 +1,158 @@
+/**
+ * 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.iotdb.tsfile.read;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import org.apache.iotdb.tsfile.common.constant.QueryConstant;
+import org.apache.iotdb.tsfile.exception.write.WriteProcessException;
+import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.iotdb.tsfile.read.common.RowRecord;
+import org.apache.iotdb.tsfile.read.expression.QueryExpression;
+import org.apache.iotdb.tsfile.read.query.dataset.QueryDataSet;
+import org.apache.iotdb.tsfile.utils.TsFileGeneratorForTest;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+
+public class ReadInPartitionTest {
+
+ private static final String FILE_PATH = TsFileGeneratorForTest.outputDataFile;
+ private TsFileSequenceReader reader;
+ private static ReadOnlyTsFile roTsFile = null;
+
+ @Before
+ public void before() throws InterruptedException, WriteProcessException, IOException {
+ TsFileGeneratorForTest.generateFile(1000000, 1024 * 1024, 10000);
+ reader = new TsFileSequenceReader(FILE_PATH);
+ }
+
+ @After
+ public void after() throws IOException {
+ roTsFile.close();
+ TsFileGeneratorForTest.after();
+ }
+
+ @Test
+ public void test1() throws IOException {
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 0L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 603242L);
+
+ roTsFile = new ReadOnlyTsFile(reader, params);
+
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ QueryExpression queryExpression = QueryExpression.create(paths, null);
+
+ QueryDataSet queryDataSet = roTsFile.query(queryExpression);
+
+ int cnt = 0;
+ while (queryDataSet.hasNext()) {
+ RowRecord r = queryDataSet.next();
+ cnt++;
+ if (cnt == 1) {
+ Assert.assertEquals("1480562618000\t0.0\t1", r.toString());
+ } else if (cnt == 9352) {
+ Assert.assertEquals("1480562664755\tnull\t467551", r.toString());
+ }
+ }
+ Assert.assertEquals(9353, cnt);
+ }
+
+ @Test
+ public void test2() throws IOException {
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 603242L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 993790L);
+
+ roTsFile = new ReadOnlyTsFile(reader, params);
+
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ QueryExpression queryExpression = QueryExpression.create(paths, null);
+
+ QueryDataSet queryDataSet = roTsFile.query(queryExpression);
+
+ int cnt = 0;
+ while (queryDataSet.hasNext()) {
+ RowRecord r = queryDataSet.next();
+ cnt++;
+ if (cnt == 1) {
+ Assert.assertEquals("1480562664765\tnull\t467651", r.toString());
+ }
+ }
+ Assert.assertEquals(1, cnt);
+ }
+
+ @Test
+ public void test3() throws IOException {
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 993790L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 1608255L);
+
+ roTsFile = new ReadOnlyTsFile(reader, params);
+
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ QueryExpression queryExpression = QueryExpression.create(paths, null);
+
+ QueryDataSet queryDataSet = roTsFile.query(queryExpression);
+
+ int cnt = 0;
+ while (queryDataSet.hasNext()) {
+ RowRecord r = queryDataSet.next();
+ cnt++;
+ if (cnt == 1) {
+ Assert.assertEquals("1480562664770\t5196.0\t467701", r.toString());
+ } else if (cnt == 9936) {
+ Assert.assertEquals("1480562711445\tnull\t934451", r.toString());
+ }
+ }
+ Assert.assertEquals(9337, cnt);
+ }
+
+ @Test
+ public void test4() throws IOException {
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 1608255L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 1999353L);
+
+ roTsFile = new ReadOnlyTsFile(reader, params);
+
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ QueryExpression queryExpression = QueryExpression.create(paths, null);
+
+ QueryDataSet queryDataSet = roTsFile.query(queryExpression);
+
+ int cnt = 0;
+ while (queryDataSet.hasNext()) {
+ RowRecord r = queryDataSet.next();
+ cnt++;
+ }
+ Assert.assertEquals(0, cnt);
+ }
+}
diff --git a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadTest.java b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadTest.java
index 260490f..e42cfd1 100755
--- a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadTest.java
+++ b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/ReadTest.java
@@ -343,7 +343,7 @@ public class ReadTest {
if (cnt == 2) {
assertEquals(1480562618990L, r.getTimestamp());
Field f2 = r.getFields().get(0);
- assertEquals(110.0, f2.getFloatV(),0.0);
+ assertEquals(110.0, f2.getFloatV(), 0.0);
}
cnt++;
}
diff --git a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/common/TimeRangeTest.java b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/common/TimeRangeTest.java
new file mode 100644
index 0000000..12e2d64
--- /dev/null
+++ b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/common/TimeRangeTest.java
@@ -0,0 +1,225 @@
+/**
+ * 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.iotdb.tsfile.read.common;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.ArrayList;
+import org.junit.Test;
+
+public class TimeRangeTest {
+
+ @Test
+ /*
+ no overlap
+ */
+ public void getRemainsTest0() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(20, 25));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 10);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), true);
+ }
+
+ @Test
+ /*
+ previous ranges contains current ranges
+ */
+ public void getRemainsTest1() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(0, 10));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(0, remainRanges.size());
+ }
+
+ @Test
+ /*
+ current ranges contains previous ranges.
+ subcase 1
+ */
+ public void getRemainsTest2() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(1, 3));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 3);
+ assertEquals(remainRanges.get(0).getMax(), 10);
+ assertEquals(remainRanges.get(0).getLeftClose(), false);
+ assertEquals(remainRanges.get(0).getRightClose(), true);
+ }
+
+ @Test
+ /*
+ current ranges contains previous ranges.
+ subcase 2
+ */
+ public void getRemainsTest3() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(5, 10));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 5);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), false);
+ }
+
+ @Test
+ /*
+ current ranges contains previous ranges.
+ subcase 3
+ */
+ public void getRemainsTest4() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(3, 8));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(2, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 3);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), false);
+ assertEquals(remainRanges.get(1).getMin(), 8);
+ assertEquals(remainRanges.get(1).getMax(), 10);
+ assertEquals(remainRanges.get(1).getLeftClose(), false);
+ assertEquals(remainRanges.get(1).getRightClose(), true);
+ }
+
+
+ @Test
+ /*
+ current ranges overlap with previous ranges.
+ subcase 1
+ */
+ public void getRemainsTest5() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(0, 5));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 5);
+ assertEquals(remainRanges.get(0).getMax(), 10);
+ assertEquals(remainRanges.get(0).getLeftClose(), false);
+ assertEquals(remainRanges.get(0).getRightClose(), true);
+ }
+
+ @Test
+ /*
+ current ranges overlap with previous ranges.
+ subcase 2
+ */
+ public void getRemainsTest6() {
+ TimeRange r = new TimeRange(3, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(0, 2));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 2);
+ assertEquals(remainRanges.get(0).getMax(), 10);
+ assertEquals(remainRanges.get(0).getLeftClose(), false);
+ assertEquals(remainRanges.get(0).getRightClose(), true);
+ }
+
+ @Test
+ /*
+ current ranges overlap with previous ranges.
+ subcase 3
+ */
+ public void getRemainsTest7() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(6, 12));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 6);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), false);
+ }
+
+ @Test
+ /*
+ current ranges overlap with previous ranges.
+ subcase 4
+ */
+ public void getRemainsTest8() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(11, 13));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(1, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 11);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), false);
+ }
+
+ @Test
+ /*
+ more than one timerange in previous ranges
+ */
+ public void getRemainsTest9() {
+ TimeRange r = new TimeRange(1, 10);
+
+ ArrayList<TimeRange> prevRanges = new ArrayList<>();
+ prevRanges.add(new TimeRange(3, 4));
+ prevRanges.add(new TimeRange(6, 8));
+
+ ArrayList<TimeRange> remainRanges = new ArrayList<>(r.getRemains(prevRanges));
+ assertEquals(3, remainRanges.size());
+ assertEquals(remainRanges.get(0).getMin(), 1);
+ assertEquals(remainRanges.get(0).getMax(), 3);
+ assertEquals(remainRanges.get(0).getLeftClose(), true);
+ assertEquals(remainRanges.get(0).getRightClose(), false);
+ assertEquals(remainRanges.get(1).getMin(), 4);
+ assertEquals(remainRanges.get(1).getMax(), 6);
+ assertEquals(remainRanges.get(1).getLeftClose(), false);
+ assertEquals(remainRanges.get(1).getRightClose(), false);
+ assertEquals(remainRanges.get(2).getMin(), 8);
+ assertEquals(remainRanges.get(2).getMax(), 10);
+ assertEquals(remainRanges.get(2).getLeftClose(), false);
+ assertEquals(remainRanges.get(2).getRightClose(), true);
+ }
+
+}
diff --git a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImplTest.java b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImplTest.java
index 1259cb7..be5037b 100644
--- a/tsfile/src/test/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImplTest.java
+++ b/tsfile/src/test/java/org/apache/iotdb/tsfile/read/controller/MetadataQuerierByFileImplTest.java
@@ -19,6 +19,7 @@
package org.apache.iotdb.tsfile.read.controller;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.iotdb.tsfile.common.constant.QueryConstant;
@@ -26,6 +27,8 @@ import org.apache.iotdb.tsfile.exception.write.WriteProcessException;
import org.apache.iotdb.tsfile.file.metadata.ChunkMetaData;
import org.apache.iotdb.tsfile.read.TsFileSequenceReader;
import org.apache.iotdb.tsfile.read.common.Path;
+import org.apache.iotdb.tsfile.read.common.TimeRange;
+import org.apache.iotdb.tsfile.read.controller.MetadataQuerier.LoadMode;
import org.apache.iotdb.tsfile.utils.TsFileGeneratorForTest;
import org.junit.After;
import org.junit.Assert;
@@ -49,8 +52,9 @@ public class MetadataQuerierByFileImplTest {
}
@Test
- public void test1() throws IOException {
+ public void test_NoPartition() throws IOException {
fileReader = new TsFileSequenceReader(FILE_PATH);
+
MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader);
List<ChunkMetaData> chunkMetaDataList = metadataQuerierByFile
.getChunkMetaDataList(new Path("d2.s1"));
@@ -60,17 +64,60 @@ public class MetadataQuerierByFileImplTest {
}
@Test
- public void test2() throws IOException {
+ public void test_InPartition() throws IOException {
fileReader = new TsFileSequenceReader(FILE_PATH);
HashMap<String, Long> params = new HashMap<>();
- params.put(QueryConstant.PARTITION_START_OFFSET, 2618269L);
- params.put(QueryConstant.PARTITION_END_OFFSET, 3006840L);
+ params.put(QueryConstant.PARTITION_START_OFFSET, 12L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 1999000L);
MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader,
params);
List<ChunkMetaData> chunkMetaDataList = metadataQuerierByFile
.getChunkMetaDataList(new Path("d2.s1"));
- Assert.assertEquals(1, chunkMetaDataList.size());
+ Assert.assertEquals(2, chunkMetaDataList.size());
+ // NOTE different systems have different exact split points.
+ // Therefore specific start and end time are not tested.
+ }
+
+ @Test
+ public void test_getTimeRangeInPartition() throws IOException {
+ fileReader = new TsFileSequenceReader(FILE_PATH);
+
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 1608255L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 3006837L);
+
+ MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader,
+ params);
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ ArrayList<TimeRange> timeRanges = metadataQuerierByFile
+ .getTimeRangeInOrPrev(paths, LoadMode.InPartition);
+ Assert.assertEquals(2, timeRanges.size());
+ // NOTE different systems have different exact split points.
+ // Therefore specific start and end time are not tested.
}
+
+ @Test
+ public void test_getTimeRangePrePartition() throws IOException {
+ fileReader = new TsFileSequenceReader(FILE_PATH);
+
+ HashMap<String, Long> params = new HashMap<>();
+ params.put(QueryConstant.PARTITION_START_OFFSET, 1608255L);
+ params.put(QueryConstant.PARTITION_END_OFFSET, 3006837L);
+
+ MetadataQuerierByFileImpl metadataQuerierByFile = new MetadataQuerierByFileImpl(fileReader,
+ params);
+ ArrayList<Path> paths = new ArrayList<>();
+ paths.add(new Path("d1.s6"));
+ paths.add(new Path("d2.s1"));
+ ArrayList<TimeRange> timeRanges = metadataQuerierByFile
+ .getTimeRangeInOrPrev(paths, LoadMode.PrevPartition);
+ Assert.assertEquals(2, timeRanges.size());
+ // NOTE different systems have different exact split points.
+ // Therefore specific start and end time are not tested.
+ }
+
}