batch computing

Updated at:

This topic describes how to use the Spark compute engine and DataFrame to perform batch computing on data in Tablestore. It also shows you how to run and debug the code in both local and cluster environments.

Prerequisites

  • Create a data table in Tablestore and write data to it. For more information, see Get started with the wide column model.

    Note

    For the schema and sample data of the search_view table, see Appendix: Sample data table.

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

  • Set up a Java development environment.

    This topic uses a Windows environment with 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 sample code

Core code

This section uses the TableStoreBatchSample class as an example to explain the core code.

Code block

Description

val df = sparkSession.read
  .format("tablestore")
  .option("instance.name", instanceName)
  .option("table.name", tableName)
  .option("endpoint", endpoint)
  .option("access.key.id", accessKeyId)
  .option("access.key.secret", accessKeySecret)
  .option("split.size.mbs", 100)
  // .option("catalog", dataCatalog)
  // The latest version allows you to use the .schema() method to replace the catalog configuration.
  .schema("salt LONG, UserId STRING, OrderId STRING, price DOUBLE, timestamp LONG")
  .load()

Loads data from a Tablestore table into a DataFrame by using the Spark DataFrameReader interface.

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

  • The instanceName, tableName, endpoint, accessKeyId, and accessKeySecret options specify the Tablestore instance name, data table name, instance endpoint, and the AccessKey ID and AccessKey Secret of an Alibaba Cloud account or a RAM user.

  • split.size.mbs specifies the split size in MB. The default value is 100. The smaller the value, the more splits are generated, resulting in more Spark tasks.

  • .schema("salt LONG, UserId STRING, OrderId STRING, price DOUBLE, timestamp LONG") specifies the schema of the data table by defining the field names and their data types. The sample data table contains five fields: salt (Long), UserId (String), OrderId (String), price (Double), and timestamp (Long).

    Note

    The latest version supports using the .schema() method in place of the catalog configuration.

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

Defines a JSON string named dataCatalog that specifies the table schema, where each field name is mapped to its data type.

df.filter("salt = 1 AND UserId = 'user_A'").show(20, truncate = false)

Filters the DataFrame to select data that meets the condition salt = 1 AND UserId = 'user_A' and displays the first 20 records.

df.createTempView("search_view")
val searchDF = sparkSession.sql("SELECT COUNT(*) FROM search_view WHERE salt = 1 AND UserId = 'user_A'")
searchDF.show()
val searchDF2 = sparkSession.sql("SELECT COUNT(*) FROM search_view WHERE salt = 1 AND UserId = 'user_A'" +
  " AND OrderId = '00002664-9d8b-441b-bad7-845202f3b142'")
searchDF2.show()
val searchDF3 = sparkSession.sql("SELECT COUNT(*) FROM search_view WHERE salt = 1 AND UserId >= 'user_A' AND UserId < 'user_B'")
searchDF3.show()

Registers the DataFrame as a temporary view named search_view and uses Spark SQL to run multiple aggregate queries that count records meeting different conditions.

  • SQL query 1: Counts the total number of records that meet the condition salt = 1 AND UserId = 'user_A'.

  • SQL query 2: Counts the total number of records that meet the condition salt = 1 AND UserId = 'user_A' AND OrderId = '00002664-9d8b-441b-bad7-845202f3b142'.

  • SQL query 3: Counts the total number of records that meet the condition salt = 1 AND UserId >= 'user_A' AND UserId < 'user_B'.

Step 4: Run and debug

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

Local development environment

This section uses IntelliJ IDEA on Windows as an example to demonstrate the debugging process.

  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 topic uses winutils 3.3.6).

    To run Spark in a Windows environment, you must install winutils.exe to resolve compatibility issues. You can download the file from the winutils GitHub project page .

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

    Note

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

    1. In the Program arguments field, specify the instance name, data table name, AccessKey ID, AccessKey Secret, and instance endpoint.

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

      In the Modify options drop-down menu, find and select the Add dependencies with "provided" scope to classpath option.

  4. Run the Scala program.

    After the program finishes running, the results are printed to the console.

    With DataFrame
    +----+------+------------------------------------+-----+-------------+
    |salt|UserId|OrderId                             |price|timestamp    |
    +----+------+------------------------------------+-----+-------------+
    |1   |user_A|00002664-9d8b-441b-bad7-845202f3b142|29.6 |1744773183629|
    |1   |user_A|9d8b7a6c-5e4f-4321-8765-0a9b8c7d6e5f|785.3|1744773190240|
    +----+------+------------------------------------+-----+-------------+
    With Spark SQL
    +--------+
    |count(1)|
    +--------+
    |       2|
    +--------+
    +--------+
    |count(1)|
    +--------+
    |       1|
    +--------+
    +--------+
    |count(1)|
    +--------+
    |       2|
    +--------+

Spark cluster environment

Important

Before you debug the code, make sure you have created a Spark cluster and that the Spark version in the cluster environment is the same as the Spark version used in the sample project. Otherwise, runtime errors might occur due to version incompatibility.

The spark-submit method is used as an example. The master in the sample code is set to local[*] by default. When you run the code on a Spark cluster, you can remove this setting and specify the master with a spark-submit parameter.

  1. Run the mvn -U clean package command to package the project. The path of 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 task by using the spark-submit command.

    spark-submit --class com.aliyun.tablestore.spark.demo.batch.TableStoreBatchSample --master yarn tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar myinstance search_view LTAI********************** DByT************************** https://myinstance.cn-hangzhou.ots.aliyuncs.com 
    [root@emr-header-1 ~]# spark-submit --class com.aliyun.tablestore.spark.demo.batch.TableStoreBatchSample --master yarn tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar
    vehicle-test OrderSource2                                                        https://vehicle-test.cn-hangzhou.ots.aliyuncs.com
    20/09/02 20:03:46 INFO [main] SparkContext: Running Spark version 2.4.3
    20/09/02 20:03:46 INFO [main] SparkContext: Submitted application: TableStoreBatchSample
    20/09/02 20:03:46 INFO [main] SecurityManager: Changing view acls to: root,*
    20/09/02 20:03:46 INFO [main] SecurityManager: Changing modify acls to: root
    20/09/02 20:03:46 INFO [main] SecurityManager: Changing view acls groups to:
    20/09/02 20:03:46 INFO [main] SecurityManager: Changing modify acls groups to:
    20/09/02 20:03:46 INFO [main] SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(root, *); groups with view permissions: Set(); users  with modify permissions: Set(root); groups with modify permissions: Set()
    20/09/02 20:03:46 INFO [main] Utils: Successfully started service 'sparkDriver' on port 33022.
    20/09/02 20:03:46 INFO [main] SparkEnv: Registering MapOutputTracker
    20/09/02 20:03:47 INFO [main] SparkEnv: Registering BlockManagerMaster
    20/09/02 20:03:47 INFO [main] BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
    20/09/02 20:03:47 INFO [main] BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
    20/09/02 20:03:47 INFO [main] DiskBlockManager: Created local directory at /tmp/blockmgr-033edd0e-4148-4708-9908-7e961076l4d5
    20/09/02 20:03:47 INFO [main] MemoryStore: MemoryStore started with capacity 366.3 MB
    20/09/02 20:03:47 INFO [main] SparkEnv: Registering OutputCommitCoordinator
    20/09/02 20:03:47 WARN [main] Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
    20/09/02 20:03:47 INFO [main] Utils: Successfully started service 'SparkUI' on port 4041.
    20/09/02 20:03:47 INFO [main] SparkUI: Bound SparkUI to 0.0.0.0, and started at http://192.168.0.180:4041
    20/09/02 20:03:47 INFO [main] SparkContext: Added JAR file:/root/tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar at spark://192.168.0.180:33022/jars/tablestore-spark-demo-1.0-SNAPSHOT-jar-with-dependencies.jar with timestamp 1599048227260
    20/09/02 20:03:47 INFO [main] Executor: Starting executor ID driver on host localhost
    20/09/02 20:03:47 INFO [main] Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 34907.
    20/09/02 20:03:47 INFO [main] NettyBlockTransferService: Server created on 192.168.0.180:34907
    20/09/02 20:03:47 INFO [main] BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
    20/09/02 20:03:47 INFO [main] BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 192.168.0.180, 34907, None)
    20/09/02 20:03:47 INFO [dispatcher-event-loop-10] BlockManagerMasterEndpoint: Registering block manager 192.168.0.180:34907 with 366.3 MB RAM, BlockManagerId(driver, 192.168.0.180, 34907, None)

Appendix: Sample data table

The following tables detail the schema and sample data for the search_view table.

Sample table schema

Parameter

Type

Description

pk

long

The primary key.

salt

long

A random salt value.

UserId

string

The user ID.

OrderId

string

The order ID.

price

double

The order amount.

timestamp

long

The timestamp.

Sample data

Pk

Salt

UserId

OrderId

Price

Timestamp

1

1

user_A

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

29.6

1744773183629

2

1

user_A

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

785.3

1744773190240

3

2

user_A

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

187

1744773195579

4

3

user_B

f1e2d3c4-b5a6-4789-90ab-123cdef45678

11.9

1744773203345

5

4

user_B

e2f3a4b5-c6d7-4890-9abc-def012345678

2547

1744773207789