stream processing

Updated at:

This topic explains how to use the DataFrame API in a Spark compute engine to perform stream processing on Tablestore data. It also covers running and debugging the code in local and Spark cluster environments.

Prerequisites

  • Create a data table and a tunnel in Tablestore, and write data to the table. For more information, see Get started with the Wide Column model and Get Started with Tunnel Service.

    Note

    See Appendix: Sample data table for the schema and sample data of the order_source_stream_view data table.

  • Create an AccessKey pair for your Alibaba Cloud account or a RAM user with permissions to access Tablestore.

  • Set up a Java development environment.

    This tutorial uses a Windows environment, JDK 1.8, IntelliJ IDEA 2024.1.2 (Community Edition), and Apache Maven as an example.

Procedure

Step 1: Download source code

Download the sample project by using Git.

git clone https://github.com/aliyun/tablestore-examples.git

If you cannot download the project due to network issues, you can download the tablestore-examples-master.zip file directly.

Step 2: Update Maven dependencies

  1. Go to the tablestore-spark-demo root directory.

    Note

    We recommend that you read the README.md file in the tablestore-spark-demo root directory to get a comprehensive overview of the project.

  2. Run the following command to install emr-tablestore-2.2.0-SNAPSHOT.jar to your local Maven repository.

    mvn install:install-file -Dfile="libs/emr-tablestore-2.2.0-SNAPSHOT.jar" -DartifactId=emr-tablestore -DgroupId="com.aliyun.emr" -Dversion="2.2.0-SNAPSHOT" -Dpackaging=jar -DgeneratePom=true

Step 3: (Optional) Modify the sample code

Key code explanation

The following section explains key parts of the StructuredTableStoreAggSQLSample code.

Code block

Description

val ordersDF = sparkSession.readStream
  .format("tablestore")
  .option("instance.name", instanceName)
  .option("table.name", tableName)
  .option("tunnel.id", tunnelId)
  .option("endpoint", endpoint)
  .option("access.key.id", accessKeyId)
  .option("access.key.secret", accessKeySecret)
  .option("maxoffsetsperchannel", maxOffsetsPerChannel) // default 10000
  .option("catalog", dataCatalog)
  .load()
  .createTempView("order_source_stream_view")

This code reads streaming data from Tablestore using Spark Structured Streaming, loads it into a streaming DataFrame, and registers the DataFrame as a temporary view named order_source_stream_view.

  • format("tablestore") loads the Spark Tablestore connector using the ServiceLoader method. For configuration details, see the META-INF.services directory.

  • instanceName, tableName, tunnelId, endpoint, accessKeyId, and accessKeySecret specify the instance name, data table name, tunnel ID, instance endpoint, AccessKey ID, and AccessKey Secret for the Alibaba Cloud account or RAM user.

  • catalog is a JSON string that defines the data schema.

  • maxoffsetsperchannel specifies the maximum number of records to read from each channel (partition) in a mini-batch. The default value is 10000.

val dataCatalog: String =
  s"""
     |{"columns": {
     |    "UserId": {"type":"string"},
     |    "OrderId": {"type":"string"},
     |    "price": {"type":"double"},
     |    "timestamp": {"type":"long"}
     | }
     |}""".stripMargin

Defines a JSON string named dataCatalog that describes the Tablestore data schema. Each key-value pair specifies a field's name and data type.

val aggDF = sparkSession.sql(
  "SELECT CAST(window.start AS String) AS begin, CAST(window.end AS String) AS end, count(*) AS count, " +
    "CAST(sum(price) AS Double) AS totalPrice FROM order_source_stream_view " +
    "GROUP BY window(to_timestamp(timestamp / 1000), '30 seconds')")
    
val query = aggDF.writeStream
  .outputMode("complete")
  .format("console")
  .option("truncate", value = false)
  .option("checkpointLocation", checkpointLocation)
  .option("triggerInterval", 10000) // custom
  .start()

Performs a time window-based aggregate operation on the streaming data using Spark SQL and outputs the results to the console.

  • SQL query

    • Time window: Groups data into 30-second time windows based on the timestamp field.

    • Aggregate operation: Counts the number of records and calculates the sum of the price field within each time window.

  • Configure the stream query output

    • outputMode("complete") sets the output mode to complete, meaning the complete aggregation result is output each time the query is triggered.

    • format("console") writes the results to the console.

    • option("truncate", value = false) disables truncation to ensure that full field values are displayed.

    • option("checkpointLocation", checkpointLocation) sets the checkpoint directory for fault tolerance and recovery.

    • option("triggerInterval", 10000) sets the trigger interval to 10 seconds.

    • start() starts the stream query.

Step 4: Run and debug

You can run and debug the code locally or in a Spark cluster. This section uses StructuredTableStoreAggSQLSample as an example to describe the debugging process.

Local environment

This section uses IntelliJ IDEA on Windows as an example to demonstrate how to debug the code.

  1. Install the Scala plugin.

    IntelliJ IDEA does not support Scala by default. You must install the Scala plugin manually.

  2. Install winutils.exe (this tutorial uses winutils 3.3.6).

    When running Spark in a Windows environment, you must also install winutils.exe for compatibility. You can download it from the GitHub project homepage.

  3. Right-click the StructuredTableStoreAggSQLSample Scala program and select Modify Run Configuration to open the Edit Run Configuration dialog box.

    Note

    The specific steps may vary slightly depending on your operating system and IntelliJ IDEA version.

    1. In the Program arguments field, specify the instance name, data table name, tunnel ID, AccessKey ID, AccessKey Secret, instance endpoint, and MaxOffsetsPerChannel parameters in order.

      myinstance order_source_stream_view 8f6a****-****-****-****-************ LTAI********************** DByT************************** https://myinstance.cn-hangzhou.ots.aliyuncs.com 10000
    2. Click Modify options, select the Add dependencies with "provided" scope to classpath checkbox, and then click OK.

  4. Run the Scala program.

    When the program finishes, the results are printed to the console.

    +-------------------+-------------------+-----+-----------------+
    |begin              |end                |count|totalPrice       |
    +-------------------+-------------------+-----+-----------------+
    |2025-04-16 11:13:30|2025-04-16 11:14:00|1    |2547.0           |
    |2025-04-16 11:13:00|2025-04-16 11:13:30|3    |984.1999999999999|
    |2025-04-16 11:12:30|2025-04-16 11:13:00|1    |29.6             |
    +-------------------+-------------------+-----+-----------------+

Spark cluster

Important

Before debugging, ensure your Spark cluster version matches the project's Spark version to avoid runtime errors from incompatibility.

This section uses the spark-submit method as an example. The master in the sample code is set to local[*] by default. When running on a Spark cluster, you can remove this setting and pass it as a spark-submit parameter.

  1. Run the mvn -U clean package command to package the project. The path to the JAR package is target/tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar.

  2. Upload the JAR package to the Driver node of the Spark cluster and submit the job using spark-submit.

    spark-submit --class com.aliyun.tablestore.spark.demo.streaming.StructuredTableStoreAggSQLSample --master yarn tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar myinstance order_source_stream_view 8f6a****-****-****-****-************ LTAI********************** DByT************************** https://myinstance.cn-hangzhou.ots.aliyuncs.com 10000

Appendix: Sample data table

The following tables describe the schema and sample data of the order_source_stream_view table.

Sample table schema

Name

Type

Description

pk

long

The primary key.

UserId

string

The user ID.

OrderId

string

The order ID.

price

double

The order amount.

timestamp

long

The timestamp.

Sample data

pk

UserId

OrderId

Price

Timestamp

1

user_A

00002664-9d8b-441b-bad7-845202f3b142

29.6

1744773175362

2

user_A

9d8b7a6c-5e4f-4321-8765-0a9b8c7d6e5f

785.3

1744773190240

3

user_A

c3d4e5f6-7a8b-4901-8c9d-0a1b2c3d4e5f

187

1744773195579

4

user_B

f1e2d3c4-b5a6-4789-90ab-123cdef45678

11.9

1744773203345

5

user_B

e2f3a4b5-c6d7-4890-9abc-def012345678

2547

1744773227789