我从来没有玩过 hstore,但是当我需要一个 EAV 列时,我会做类似的事情,例如:
create index on product_eav (eav_value) where (eav_type = 'int');
这样做的限制是您需要在查询中明确使用它,即此查询不会使用上述索引:
select product_id
from product_eav
where eav_name = 'size'
and eav_value = :size;
但是这个会:
select product_id
from product_eav
where eav_name = 'size'
and eav_value = :size
and type = 'int';
在您的示例中,它可能更像:
create index on product ((data->'size')::int) where (data->'size' is not null);
这应该避免在没有大小条目时添加对索引的引用。根据您使用的 PG 版本,可能需要像这样修改查询:
select product_id
from products
where data->'size' is not null
and data->'size' = :size;
常规索引和部分索引之间的另一个重大区别是后者不能在表定义中强制执行唯一约束。这将成功:
create unique index foo_bar_key on foo (bar) where (cond);
以下不会:
alter table foo add constraint foo_bar_key unique (bar) where (cond);
但这会:
alter table foo add constraint foo_bar_excl exclude (bar with =) where (cond);