当不满足所有选择标准时,Spark 会选择哪个连接?

che*_*mos 1 join apache-spark apache-spark-sql

我们知道在 Spark 中有三种类型的连接——广播连接?随机加入和排序合并加入?

  • 当小表加入大表时?使用广播加入?
  • 当小表比 BroadcastJoinThreshold 大时?使用 Shuffle Join?
  • 当大表加入?和加入键可以排序?使用排序合并加入?

两个大表的join,join key无法排序的情况怎么办?Spark 会选择哪种连接类型?

maz*_*cha 6

Spark 3.0 及更高版本支持以下类型的连接:

  • 广播哈希连接 (BHJ)
  • 随机哈希连接
  • 随机排序合并连接 (SMJ)
  • 广播嵌套循环连接 (BNLJ)
  • 笛卡尔积连接

他们的选择最好在源代码中概述SparkStrategies.scala

  /**
   * Select the proper physical plan for join based on join strategy hints, the availability of
   * equi-join keys and the sizes of joining relations. Below are the existing join strategies,
   * their characteristics and their limitations.
   *
   * - Broadcast hash join (BHJ):
   *     Only supported for equi-joins, while the join keys do not need to be sortable.
   *     Supported for all join types except full outer joins.
   *     BHJ usually performs faster than the other join algorithms when the broadcast side is
   *     small. However, broadcasting tables is a network-intensive operation and it could cause
   *     OOM or perform badly in some cases, especially when the build/broadcast side is big.
   *
   * - Shuffle hash join:
   *     Only supported for equi-joins, while the join keys do not need to be sortable.
   *     Supported for all join types except full outer joins.
   *
   * - Shuffle sort merge join (SMJ):
   *     Only supported for equi-joins and the join keys have to be sortable.
   *     Supported for all join types.
   *
   * - Broadcast nested loop join (BNLJ):
   *     Supports both equi-joins and non-equi-joins.
   *     Supports all the join types, but the implementation is optimized for:
   *       1) broadcasting the left side in a right outer join;
   *       2) broadcasting the right side in a left outer, left semi, left anti or existence join;
   *       3) broadcasting either side in an inner-like join.
   *     For other cases, we need to scan the data multiple times, which can be rather slow.
   *
   * - Shuffle-and-replicate nested loop join (a.k.a. cartesian product join):
   *     Supports both equi-joins and non-equi-joins.
   *     Supports only inner like joins.
   */
object JoinSelection extends Strategy with PredicateHelper { ...
Run Code Online (Sandbox Code Playgroud)

如前所述,应用选择的结果不仅取决于表的大小和键的可排序性,还取决于连接类型 ( INNER, LEFT/RIGHT, FULL) 和连接键条件 (equi- vs non-equi/theta)。总的来说,在您的情况下,您可能会看到 Shuffle Hash 或 Broadcast Nested Loop。