Skip to content

SQL性能调优 ​

1.优化器提示 ​

查询优化器会尝试执行最优的执行计划,但是如果用户能更深入地了解集群的数据设计、程序设计或数据分布,就可以通过 SQL 提示帮助优化器更合理地进行优化或更快地构建执行计划。

提示

SQL 提示是可选的,在某些场景可能会被跳过。

1.1.提示格式 ​

SQL 提示由特殊注释 /*+ HINT */ 定义,称为提示块。提示名前后的空格是必需的,提示块必须放在运算符之后,一个关系运算符不支持多个提示。

示例:

sql
SELECT /*+ NO_INDEX */ T1.* FROM TBL1 where T1.V1=? and T1.V2=?

1.1.1.提示参数 ​

如果需要,提示参数将放在提示名后的括号中,并用逗号分隔。

提示参数可以加引号,加引号的参数区分大小写,带引号和不带引号的参数不能是相同的提示定义。

示例:

sql
SELECT /*+ FORCE_INDEX(TBL1_IDX2,TBL2_IDX1) */ T1.V1, T2.V1 FROM TBL1 T1, TBL2 T2 WHERE T1.V1 = T2.V1 AND T1.V2 > ? AND T2.V2 > ?;

SELECT /*+ FORCE_INDEX('TBL2_idx1') */ T1.V1, T2.V1 FROM TBL1 T1, TBL2 T2 WHERE T1.V1 = T2.V1 AND T1.V2 > ? AND T2.V2 > ?;

1.2.提示错误 ​

优化器会尽可能尝试启用每个提示及其参数。但是在如下场景中,它会跳过提示或提示参数:

  • 不支持该提示;
  • 未传入必要的参数;
  • 提示不支持参数,但是传入了参数;
  • 提示参数不正确或引用了不存在的对象,例如不存在的索引或表;
  • 当前提示或当前参数与之前的不兼容,例如强制使用和禁用同一个索引。

如果FORCE_INDEX提示引用的索引不存在,会抛出如下的错误:

Hints mentioned indexes "IDX_NOT_FOUND1", "IDX_NOT_FOUND2" were not found.

1.3.支持的提示 ​

1.3.1.FORCE_INDEX/NO_INDEX ​

强制或禁用索引扫描。

参数:

  • 空,强制对每个基础表进行索引扫描,优化器将选择任何可用的索引,或者禁用所有索引;
  • 使用某个索引名,或跳过此索引;
  • 多个索引名,它们可以与不同的表相关,优化器将选择要扫描的索引或跳过所有索引。

示例:

sql
SELECT /*+ FORCE_INDEX */ T1.* FROM TBL1 T1 WHERE T1.V1 = T2.V1 AND T1.V2 > ?;

SELECT /*+ FORCE_INDEX(TBL1_IDX2, TBL2_IDX1) */ T1.V1, T2.V1 FROM TBL1 T1, TBL2 T2 WHERE T1.V1 = T2.V1 AND T1.V2 > ? AND T2.V2 > ?;

SELECT /*+ NO_INDEX */ T1.* FROM TBL1 T1 WHERE T1.V1 = T2.V1 AND T1.V2 > ?;

SELECT /*+ NO_INDEX(TBL1_IDX2, TBL2_IDX1) */ T1.V1, T2.V1 FROM TBL1 T1, TBL2 T2 WHERE T1.V1 = T2.V1 AND T1.V2 > ? AND T2.V2 > ?;

提示

查询不能同时具有 FORCE_INDEX 和 NO_INDEX 提示。

2.使用EXPLAIN语句 ​

2.1.EXPLAIN PLAN FOR语句 ​

Ignite 支持EXPLAIN PLAN FOR语句,用于读取查询的执行计划。

可以使用该命令分析查询,然后做可能的优化,例如:

sql
EXPLAIN PLAN FOR SELECT name FROM Person WHERE age = 26;

解析的结果可能如下所示:

╔═══════════════════════════════╗
║ PLAN                          ║
╠═══════════════════════════════╣
║ Exchange                      ║
║     distribution: single      ║
║     est. row count: 333000    ║
║   TableScan                   ║
║       table: [PUBLIC, PERSON] ║
║       filters: =(AGE, 26)     ║
║       fields: [$f0]           ║
║       projects: [NAME]        ║
║       est. row count: 333000  ║
╚═══════════════════════════════╝

2.2.EXPLAIN MAPPING FOR语句 ​

Ignite 支持 EXPLAIN MAPPING FOR 语句,用于跟踪查询如何拆分以及子查询在哪些节点上执行。

如果需要了解查询如何拆解并在分布式集群的多个节点间执行,可以使用这个命令。

sql
EXPLAIN MAPPING FOR SELECT name FROM Person WHERE age = 26;

输出大致如下所示:

╔═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╗
║ PLAN                                                                                                                                                                                              ║
╠═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╣
║ Fragment#0 root                                                                                                                                                                                   ║
║   executionNodes: [defaultNode]                                                                                                                                                                   ║
║   remoteFragments: [1]                                                                                                                                                                            ║
║   exchangeSourceNodes: {1=[defaultNode]}                                                                                                                                                          ║
║   tree:                                                                                                                                                                                           ║
║     Receiver(sourceFragment=1, exchange=1, distribution=single)                                                                                                                                   ║
║                                                                                                                                                                                                   ║
║ Fragment#1                                                                                                                                                                                        ║
║   targetNodes: [defaultNode]                                                                                                                                                                      ║
║   executionNodes: [defaultNode]                                                                                                                                                                   ║
║   tables: [PERSON]                                                                                                                                                                                ║
║   partitions: {defaultNode=[0:12, 1:12, 2:12, 3:12, 4:12, 5:12, 6:12, 7:12, 8:12, 9:12, 10:12, 11:12, 12:12, 13:12, 14:12, 15:12, 16:12, 17:12, 18:12, 19:12, 20:12, 21:12, 22:12, 23:12, 24:12]} ║
║   tree:                                                                                                                                                                                           ║
║     Sender(targetFragment=0, exchange=1, distribution=single)                                                                                                                                     ║
║       TableScan(name=PUBLIC.PERSON, source=2, partitions=25, distribution=random)                                                                                                                 ║
╚═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╝

3.查询批处理 ​

Ignite 处理批量请求的速度比单个请求快,因此建议尽可能使用多语句执行。

当一次调用执行多个语句时,类似的操作会自动地批量处理,因此在编写执行多种不同操作的大型脚本时,建议按以下顺序进行:

  • 所有必要的DDL操作;
  • 分配访问权限;
  • 将数据加载到表中。

由于当第一页准备返回时,每条语句的执行都被视为完成,因此在处理大型数据集时,SELECT语句可能会受到同一脚本中后续语句的影响。

4.关联子查询的性能考量 ​

Ignite 支持关联子查询,但某些复杂关联子查询的性能可能不足,尤其是在高流量事务或分析工作负载中使用时。

4.1.什么是关联子查询 ​

相关子查询是指依赖外部查询值执行的子查询。它对外层查询的每一行进行一次评估。

例如,对于如下的模式:

sql
CREATE TABLE projects (id INT PRIMARY KEY, name VARCHAR);
CREATE TABLE employees (id INT PRIMARY KEY, department_id INT, name VARCHAR, salary DECIMAl);
CREATE TABLE departments (id INT PRIMARY KEY, name VARCHAR);
CREATE TABLE assignments (project_id INT, employee_id INT, PRIMARY KEY (project_id, employee_id));

相关子查询可能如下:

sql
SELECT e.name,
       (SELECT COUNT(*)
          FROM assignments a
         WHERE a.employee_id = e.id
       ) AS project_count
FROM employees e;

这里,子查询引用的e.id来自外部查询,意味着对每一行员工都要重新评估,导致N个员工执行N个独立的子查询。

4.2.性能影响 ​

在Ignite 3 中,重复的子查询执行不会自动优化,因此:

  • 标量子查询可能会成为瓶颈;
  • 即使是小表,反复查询也会导致CPU和内存消耗过高;
  • 某些查询可能比预期慢。

4.3.提升性能 ​

一般来说,带有廉价标量子查询(如单行索引查找)的高度选择性外部查询表现良好,这里有一个示例:

sql
-- This query returns an employee along with the name of the department they belong to.
-- It uses a correlated scalar subquery to resolve the department name.
--
-- Note the predicate `e.id = ?`, which filters by the employee's primary key.
-- This makes the outer query highly selective —- typically returning only a single row.
--
-- Because the subquery is evaluated only once (or a very small number of times),
-- using a correlated scalar subquery is safe and has negligible performance impact
-- in this case. There's no need to rewrite it using a join.
SELECT e.*,
       (SELECT name
          FROM departments
         WHERE id = e.department_id
       ) AS employees_department
  FROM employees e
 WHERE e.id = ?;

类似查询但无谓词可能导致性能下降。如果带谓词的查询耗时0.007s,类似无谓词的查询耗时可达2.4s。

这里还有一个示例:

sql
-- This query returns all employees along with the name of the department they
-- belong to.
SELECT e.*,
       (SELECT name
          FROM departments
         WHERE id = e.department_id
       ) AS employees_department
  FROM employees e;

上述查询可以很容易地用常规JOIN重写:

sql
-- Equivalent query to the previous example, but uses a `LEFT JOIN` instead of a
-- correlated subquery. This rewrite is valid as long as the subquery in the original
-- version would return at most one row.
--
-- If multiple rows exist in the `departments` table for the same `id`, the original
-- scalar subquery would result in a runtime error (due to a non-scalar result), while
-- the join version would produce duplicated rows in the output.
--
-- In our case, `departments.id` is a primary key, so the join is safe and will return
-- at most one matching department per employee.
--
-- A `LEFT JOIN` is used to ensure that employees with no matching department are still
-- returned. If it's guaranteed that every employee has a valid department reference,
-- an `INNER JOIN` may be used instead, which is slightly more efficient.
SELECT e.*,
       d.name AS employees_department
  FROM employees e
  LEFT JOIN departments d ON d.id = e.department_id;

在同一环境中重写查询速度会明显提升。

4.4.改进查询示例 ​

第一个示例演示了如何在不逐行评估的情况下正确查询数据库:

sql
-- This query returns all employees without assigned projects.
--
-- Finishes in 3.2s (assuming there is an index on `assignments(employee_id)`;
-- without the index, execution time increases significantly —- up to 12s).
SELECT e.id, e.name
FROM employees e
WHERE NOT EXISTS (
    SELECT 1
    FROM assignments a
    WHERE a.employee_id = e.id
);

-- Equivalent query without correlated subqueries.
-- Instead of evaluating a subquery for each row, we join the tables and compute
-- the number of assignments using aggregation. It is important to include all
-- columns that form a unique key from the outer table in the `GROUP BY` clause.
-- Otherwise, multiple rows may be grouped together incorrectly, potentially
-- affecting the result. If you're unsure about the uniqueness of specific columns,
-- include all columns from the table's `PRIMARY KEY`.
--
-- A `LEFT JOIN` is used because we want to retain employees even when there is
-- no matching assignment. An `INNER JOIN` would exclude those employees.
--
-- The `HAVING COUNT(a.employee_id) = 0` clause checks for the absence of matches.
-- You must count a column from the right-hand side of the join that is guaranteed
-- to be non-null. In this case, `a.employee_id` is suitable because the `JOIN`
-- condition (`a.employee_id = e.id`) ensures that only non-null `employee_id`s
-- are matched; nulls are excluded during the join phase.
--
-- Finishes in 0.04s.
SELECT e.id, e.name
  FROM employees e
  LEFT JOIN assignments a ON a.employee_id = e.id
 GROUP BY e.id, e.name
HAVING COUNT(a.employee_id) = 0;

-- Similar query, but returns only employees who have at least one project assigned.
-- Note the use of `INNER JOIN`: since we are only interested in employees with a
-- matching assignment, an inner join is both sufficient and more efficient in this case.
--
-- The `HAVING COUNT(a.employee_id) > 0` condition ensures that only employees
-- with one or more matching rows in the `assignments` table are returned.
-- As with the previous example, `a.employee_id` is safe to count because it cannot be null
-- due to the join condition (`a.employee_id = e.id`) filtering out nulls.
--
-- Finishes in 0.03s.
SELECT e.id, e.name
  FROM employees e
  JOIN assignments a ON a.employee_id = e.id
 GROUP BY e.id, e.name
HAVING COUNT(a.employee_id) > 0;

这个示例演示了通过改进查询可以带来的显著性能提升:

sql
-- This query returns all employees whose salary is the minimum within their department.
--
-- Finishes in 18s.
SELECT e.*
  FROM employees e
 WHERE e.salary = (SELECT MIN(salary) FROM employees WHERE department_id = e.department_id);

-- Equivalent query without a correlated subquery.
-- Instead of comparing each employee's salary with a scalar subquery result,
-- we precompute the minimum salary per department using a grouped subquery,
-- and then join it back to the employees table.
--
-- This rewrite is safe because:
--   - For each department, we compute the minimum salary exactly once.
--   - The join condition ensures we only return employees whose salary matches
--     the minimum salary for their department.
--   - No grouping is needed on the outer query because we're performing an equality match
--     on both `department_id` and the computed minimum salary.
--
-- This approach avoids per-row subquery evaluation and leverages set-based operations,
-- which are significantly faster.
--
-- Finishes in 0.02s.
SELECT e.*
  FROM employees e
  JOIN (
      SELECT department_id, MIN(salary) AS min_salary
        FROM employees
       GROUP BY department_id
  ) AS min_salaries_by_department
    ON e.department_id = min_salaries_by_department.department_id
   AND e.salary = min_salaries_by_department.min_salary;

5.删除缓存的计划 ​

警告

这是一个实验性的API。

由于优化查询执行计划是一个资源密集型操作,Ignite 会缓存该计划并用于后续相关查询。随着数据更新,计划可能会过时,需要重新计算。计划默认在ignite.planner.planCacheExpiresAfterSeconds参数指定的时间(默认为1800秒)后到期。

要强制提前更新,可以使用命令行工具的sql planner invalidate-cache命令:

shell
sql planner invalidate-cache --tables=PUBLIC.Person

18624049226