【问题标题】:Hibernate with partitioned table使用分区表休眠
【发布时间】:2017-02-03 11:36:16
【问题描述】:
使用数据库 postgresql 9.5。
我有一个表 employee_shift,其中行 110966498,因此为了改进插入,我已经将此表分区了 20 年(2000 年 1 月至 2020 年 12 月,即到目前为止 240 个分区表)。这是表格中column 的日期。
现在我的插入速度更快(通过本机查询完成),但我现有的 DAO 层使用 HQL,它命中 employee_shift 表而不是命中 employee_shift_2010_10(年月),因此我的选择语句相对要慢得多,因为它检查所有分区。
如果我使用使用date 列的select 语句,hibernate 是否可以直接点击employee_shift_2010_10?
在这种情况下,我还有哪些其他选项可以让我的选择更快?
【问题讨论】:
标签:
postgresql
hibernate
partitioning
database-partitioning
【解决方案1】:
可能您没有为继承的表设置约束,或者您使用参数化查询。
CREATE TABLE a (id serial PRIMARY KEY, ts timestamp);
CREATE INDEX a_ts ON a (ts);
CREATE TABLE a_2010 ( CONSTRAINT data_2011_check CHECK (ts >= '2010-01-01 00:00:00'::timestamp AND ts < '2011-01-01 00:00:00'::timestamp)) INHERITS (a);
CREATE TABLE a_2011 ( CONSTRAINT data_2012_check CHECK (ts >= '2011-01-01 00:00:00'::timestamp AND ts < '2012-01-01 00:00:00'::timestamp)) INHERITS (a);
CREATE TABLE a_2012 ( CONSTRAINT data_2013_check CHECK (ts >= '2012-01-01 00:00:00'::timestamp AND ts < '2013-01-01 00:00:00'::timestamp)) INHERITS (a);
CREATE TABLE a_2013 ( CONSTRAINT data_2014_check CHECK (ts >= '2013-01-01 00:00:00'::timestamp AND ts < '2014-01-01 00:00:00'::timestamp)) INHERITS (a);
CREATE INDEX a_ts_2010 ON a_2010 (ts);
CREATE INDEX a_ts_2011 ON a_2011 (ts);
CREATE INDEX a_ts_2012 ON a_2012 (ts);
CREATE INDEX a_ts_2013 ON a_2013 (ts);
之后,您可以看到 postgresql 通过约束检查继承的表。约束不能重叠。
EXPLAIN ANALYZE SELECT * FROM a WHERE ts = '2011-02-01 00:00:00';
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
Append (cost=0.00..14.79 rows=11 width=12) (actual time=0.006..0.006 rows=0 loops=1)
-> Seq Scan on a (cost=0.00..0.00 rows=1 width=12) (actual time=0.003..0.003 rows=0 loops=1)
Filter: (ts = '2011-02-01 00:00:00'::timestamp without time zone)
-> Bitmap Heap Scan on a_2011 (cost=4.23..14.79 rows=10 width=12) (actual time=0.003..0.003 rows=0 loops=1)
Recheck Cond: (ts = '2011-02-01 00:00:00'::timestamp without time zone)
-> Bitmap Index Scan on a_ts_2011 (cost=0.00..4.23 rows=10 width=0) (actual time=0.003..0.003 rows=0 loops=1)
Index Cond: (ts = '2011-02-01 00:00:00'::timestamp without time zone)
Planning time: 1.148 ms
Execution time: 0.046 ms
(9 rows)