PostgreSQL中表达式索引的实际限制

我需要使用HSTORE类型和按键索引来存储数据.

CREATE INDEX ix_product_size ON product(((data->'Size')::INT))
CREATE INDEX ix_product_color ON product(((data->'Color')))
etc.

使用表达式索引有哪些实际限制?在我的例子中,可能有数百种不同类型的数据,因此有数百个表达式索引.每个insert,update和select查询都必须处理这些索引才能选择正确的索引.

解决方法

我从来没有玩过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);

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...