【发布时间】:2021-11-04 22:41:31
【问题描述】:
我正在尝试从 1000 万行表中获取排序和过滤的数据。在这种情况下,ordered by 工作的问题非常慢。过滤组合的数量非常多,我无法预测它们都以正确的顺序创建缓存。此外,我的数据可以经常更改。换句话说,我真的需要对每个查询的数据进行排序。
我尝试用谷歌搜索它并意识到索引和其他优化对订购没有帮助。我对吗?快速获取有序数据的最佳方式是什么?在postgres中可以吗?我应该为此使用不同的工具吗?也许是非关系数据库中的 ETL 或类似的东西?
简单查询示例:
EXPLAIN ANALYZE
SELECT *
FROM offers
WHERE
offers.attributes ->> 'width' = '190'
AND offers.attributes ->> 'height' = '55'
AND offers.attributes ->> 'diameter' = '16'
ORDER BY price
解释分析输出:
Sort (cost=463529.78..463529.78 rows=1 width=248) (actual time=3083.447..3084.143 rows=12420 loops=1)
Sort Key: price
Sort Method: quicksort Memory: 6530kB
-> Gather (cost=1000.00..463529.77 rows=1 width=248) (actual time=0.327..3078.755 rows=12420 loops=1)
Workers Planned: 2
Workers Launched: 2
-> Parallel Seq Scan on offers (cost=0.00..462529.67 rows=1 width=248) (actual time=4.826..3072.672 rows=4140 loops=3)
Filter: (((attributes ->> 'width'::text) = '190'::text) AND ((attributes ->> 'height'::text) = '55'::text) AND ((attributes ->> 'diameter'::text) = '16'::text))
Rows Removed by Filter: 3329193
Planning Time: 0.256 ms
Execution Time: 3084.612 ms
所有表索引
create index offers_attribu_5d15b4_gin
on offers using gin (attributes);
create index offers_created_ae6fa523
on offers (created);
create index offers_updated_c723e738
on offers (updated);
create index offers_quantity_dc0026a6
on offers (quantity);
create index offers_model_id_8846a913
on offers (model_id);
create index offers_price_list_id_1f3d95de
on offers (price_list_id);
create index offers_price_ids
on offers (price);
create index offers_model_price_idx
on offers (model_id, price);
create index offers_json_price_idx
on offers (attributes, price);
create index offers_json_model_idx
on offers (attributes, model_id);
create index offers_price_idx
on offers (price);
【问题讨论】:
-
"过滤组合的数量很大" 但是选择性呢?如果一个条件消除了 99.999% 的数据,而所有其余条件加起来只删除了剩下的 50%,那么您几乎可以忽略其余条件。
-
@a_horse_with_no_name 完成
-
@jjanes 过滤后还剩下大约 10 万行
-
@jjanes 当然取决于过滤器,例如可以是 10 000,但仍然很慢
-
在您的示例中,排序花费的时间不到总时间的 1%。不值得担心。