When two tables are joined in Spark SQL, the broadcast function (see section "Using Broadcast Variables") can be used to broadcast tables to each node. This minimizes shuffle operations and improves task execution efficiency.
The join operation refers to the inner join operation only.
The following describes how to optimize the join operation in Spark SQL. Assume that both tables A and B have the name column. Join tables A and B as follows:
Estimate the table size based on the size of data loaded each time.
You can also check the table size in the directory of the Hive database. In the hive-site.xml configuration file of Spark, view the Hive database directory, which is /user/hive/warehouse by default. The default Hive database directory for multi-instance Spark is /user/hive/warehouse, for example, /user/hive1/warehouse.
<property> <name>hive.metastore.warehouse.dir</name> <value>${test.warehouse.dir}</value> <description></description> </property>
Run the hadoop command to check the size of the table. For example, run the following command to view the size of table A:
hadoop fs -du -s -h ${test.warehouse.dir}/a
To perform the broadcast operation, ensure that at least one table is not empty.
The threshold for triggering broadcast for a table is 10485760 (that is, 10 MB) in Spark. If either of the table sizes is smaller than 10 MB, skip this step.
Table 1 lists configuration parameters of the threshold for automatic broadcasting.
Parameter |
Default Value |
Description |
---|---|---|
spark.sql.autoBroadcastJoinThreshold |
10485760 |
Indicates the maximum value for the broadcast configuration when two tables are joined.
For details, visit https://spark.apache.org/docs/3.1.1/sql-programming-guide.html. |
Methods for configuring the threshold for automatic broadcasting:
spark.sql.autoBroadcastJoinThreshold = <size>
SET spark.sql.autoBroadcastJoinThreshold=<size>;
SELECT A.name FROM B JOIN A ON A.name = B.name;
SELECT A.name FROM A JOIN B ON A.name = B.name;
Compare the size of the field involved in the query with the threshold.
A task is ended if a timeout occurs during the execution of the to-be-broadcasted table.
By default, BroadCastJoin allows only 5 minutes for the to-be-broadcasted table calculation. If the time is exceeded, a timeout will occur. However, the broadcast task of the to-be-broadcasted table calculation is still being executed, resulting in resource waste.
The following methods can be used to address this issue: