【发布时间】:2019-06-26 10:44:44
【问题描述】:
我有具有以下结构的大表(100M 记录)。
length | created_at
-----------+-------------------------------
506225551 | 2018-12-29 02:08:34.116618
133712971 | 2018-10-19 21:20:14.568936
608443439 | 2018-12-14 03:22:55.141416
927160571 | 2019-01-30 00:51:41.639126
407033524 | 2018-11-16 21:26:41.523047
506008096 | 2018-11-17 00:07:42.839919
457719749 | 2018-11-12 02:32:53.116225
0 < length < 1000000000'2017-01-01' < created_at < '2019-02-01'-
length和created_at的数据均匀分布。
我想运行这样的查询
SELECT * FROM tbl WHERE length BETWEEN 2000000 and 3000000 ORDER BY created_at DESC
2000000 到 3000000 之间有 100K 个结果,所以我想使用索引进行选择和排序。
我已经尝试过这些方法
1。简单的 BTREE 索引
create index on tbl(length);
这适用于length 的短距离,但我不能使用这个索引来记录订购记录。
2。多列BTREE索引
create index on tbl(length, created_at);
这个索引我只能用于这样的查询
SELECT * FROM tbl WHERE length = 2000000 ORDER BY created_at DESC
3。带有 btree_gist 扩展名的 GIST 索引。我希望,这个索引应该可以工作。
create index on tbl using gist(length, created_at);
但它没有。即使是这样的简单查询,我也无法使用此索引。
test=# explain analyze select * from gist_test where a = 345 order by c desc;
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------
Sort (cost=25706.37..25730.36 rows=9597 width=12) (actual time=4.839..5.568 rows=10000 loops=1)
Sort Key: c DESC
Sort Method: quicksort Memory: 853kB
-> Bitmap Heap Scan on gist_test (cost=370.79..25071.60 rows=9597 width=12) (actual time=1.402..2.869 rows=10000 loops=1)
Recheck Cond: (a = 345)
Heap Blocks: exact=152
-> Bitmap Index Scan on gist_test_a_b_c_idx (cost=0.00..368.39 rows=9597 width=0) (actual time=1.384..1.384 rows=10000 loops=1)
Index Cond: (a = 345)
Planning time: 0.119 ms
Execution time: 6.271 ms
我只能将此索引用作一列上的简单 BTREE。
那么,我该如何解决这个问题呢?
也许没有可以处理此类查询的 SQL 数据库?
【问题讨论】:
-
我认为不可能创建允许查询任何
length范围的索引。如果可能的范围有限(例如最多 100 个),您可以为每个可能的范围创建部分索引。
标签: postgresql performance indexing nosql b-tree