use*_*114 1 postgresql performance database-performance query-performance pg-trgm
我正在尝试使用扩展来加速Postgres 中的一些文本匹配pg_trgm:
CREATE TABLE test3 (id bigint, key text, value text);
insert into test3 values (1, 'first 1', 'second 3');
insert into test3 values (2, 'first 1', 'second 2');
insert into test3 values (2, 'first 2', 'second 3');
insert into test3 values (3, 'first 1', 'second 2');
insert into test3 values (3, 'first 1', 'second 3');
insert into test3 values (4, 'first 2', 'second 3');
insert into test3 values (4, 'first 2', 'second 3');
insert into test3 values (4, 'first 1', 'second 2');
insert into test3 values (4, 'first 1', 'second 2');
-- repeat the above 1,000,000x times, to have more rows for benchmarking
insert into test3(id, key, value) select id, key, value from test3 cross join generate_series(1, 1000000);
Run Code Online (Sandbox Code Playgroud)
现在我查询这个表ILIKE:
select count(*) from test3 where key = 'first 1' and value ilike '%nd 3%';
Time: 918.265 ms
Run Code Online (Sandbox Code Playgroud)
为了查看索引是否会加快速度,我pg_trgm在key和value列上都添加了:
CREATE extension if not exists pg_trgm;
CREATE INDEX test3_key_trgm_idx ON test3 USING gin (key gin_trgm_ops);
CREATE INDEX test3_value_trgm_idx ON test3 USING gin (value gin_trgm_ops);
Run Code Online (Sandbox Code Playgroud)
但是查询仍然需要相同的时间,并EXPLAIN ANALYZE显示索引根本没有被使用:
explain analyze select count(*) from test3 where key = 'first 1' and value ilike '%nd 3%';
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------
Finalize Aggregate (cost=126905.14..126905.15 rows=1 width=8) (actual time=1017.666..1017.667 rows=1 loops=1)
-> Gather (cost=126904.93..126905.14 rows=2 width=8) (actual time=1017.505..1018.778 rows=3 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Partial Aggregate (cost=125904.93..125904.94 rows=1 width=8) (actual time=1010.862..1010.862 rows=1 loops=3)
-> Parallel Seq Scan on test3 (cost=0.00..122427.06 rows=1391148 width=0) (actual time=0.041..973.550 rows=666667 loops=3)
Filter: ((value ~~* '%nd 3%'::text) AND (key = 'first 1'::text))
Rows Removed by Filter: 2333336
Planning Time: 0.266 ms
Execution Time: 1018.814 ms
Time: 1049.413 ms (00:01.049)
Run Code Online (Sandbox Code Playgroud)
注意顺序扫描。是什么赋予了?
没关系,我发现了问题。
查询计划器比我的玩具测试集更聪明;看到大多数行与查询匹配,它进行了顺序扫描。
如果我ilike '%nd 0%'改为尝试,则没有行匹配且 EXPLAIN ANALYZE 报告Bitmap Index Scan on test3_value_trgm_idx正确。
因此,以这种方式规范化原始 JSONB 是有效的。但我也会尝试寻找和比较另一种方式,使用正则表达式 over TEXT,以避免必须创建和维护另一个表。
| 归档时间: |
|
| 查看次数: |
1306 次 |
| 最近记录: |