为什么 Spanner 在 LIKE 中使用下划线执行完整 table 扫描,而使用 % 利用索引?

Why Spanner performs full table scan using a underscore in a LIKE, while using % leverages the index?

在查询中,如果我在主键上使用 LIKE '<value>%' 它执行良好,使用索引:

Operator | Rows returned | Executions | Latency
-- | -- | -- | --
 Serialize Result   32  1   1.80 ms
 Sort   32  1   1.78 ms
 Hash Aggregate 32  1   1.73 ms
 Distributed union  32  1   1.61 ms
 Hash Aggregate 32  1   1.56 ms
 Distributed union  128 1   1.34 ms
 Compute    -   -   -
 FilterScan 128 1   1.33 ms
 Table Scan: <tablename>    128 1   1.30 ms

然而,使用 LIKE '<value>_' 执行完整 table 扫描:

Operator | Rows returned | Executions | Latency
-- | -- | -- | --
Serialize Result | 32 | 1 | 76.27 s
Sort | 32 | 1 | 76.27 s
Hash Aggregate | 32 | 1 | 76.27 s
Distributed union | 32 | 1 | 76.27 s
Hash Aggregate | 32 | 2 | ~72.18 s
Distributed union | 128 | 2 | ~72.18 s
Compute | - | - | -
FilterScan | 128 | 2 | ~72.18 s
Table Scan: <tablename> (full scan: true) | 13802624 | 2 | ~69.97 s

查询如下所示:

SELECT
    'aggregated-quadkey AS quadkey' AS quadkey, day,
    SUM(a_value_1), SUM(a_value_2), AVG(a_value_3), SUM(a_value_4), SUM(a_value_5), AVG(a_value_6), AVG(a_value_6), AVG(a_value_7), SUM(a_value_8), SUM(a_value_9), AVG(a_value_10), SUM(a_value_11), SUM(a_value_12), AVG(a_value_13), AVG(a_value_14), AVG(a_value_15), SUM(a_value_16), SUM(a_value_17), AVG(a_value_18), SUM(a_value_19), SUM(a_value_20), AVG(a_value_21), AVG(a_value_22), AVG(a_value_23)
FROM <tablename>
WHERE quadkey LIKE '03201012212212322_'
GROUP BY quadkey, day ORDER BY day

对于前缀匹配 LIKE 模式 (column LIKE 'xxx%'),查询优化器在内部将条件转换为 STARTS_WITH(column, 'xxx'),然后使用索引。

所以原因可能是因为查询优化器不够智能 转换匹配 LIKE 模式的精确长度前缀

column LIKE 'xxx_'

合并成条件:

(STARTS_WITH(column, 'xxx') AND CHAR_LENGTH(column)=4)

类似地,一个模式如

`column LIKE 'abc%def'`

未优化成组合条件:

`(STARTS_WITH(column,'abc') AND ENDS_WITH(column,'def'))`.

您始终可以通过使用上述条件优化 SQL 代中的查询来解决此问题。

(假设 LIKE 模式是查询中的字符串值,而不是参数 - LIKE 使用参数无法优化,因为在查询编译时不知道模式。)

感谢您报告此事!我在积压中添加了这个重写。同时,您可以使用 STARTS_WITH 和 CHAR_LENGTH 来解决这个问题,正如 RedPandaCurios 所建议的那样。