PostgreSQL hstore数组列的索引

Jac*_*icz 3 postgresql indexing hstore

我知道你可以在hstore列的字段上创建索引.我知道你也可以在数组列上创建一个GIN索引.

但是在hstore数组上创建索引的语法是什么?

例如

CREATE TABLE customer (
    pk serial PRIMARY KEY,
    customer hstore,
    customer_purchases hstore[]
);
Run Code Online (Sandbox Code Playgroud)

假设客户购买hstore可能是哈希

productId -> 1
price -> 9.99
Run Code Online (Sandbox Code Playgroud)

我在customer_purchases hstore []中有一组数组

我想在customer.customer_purchases [] - > productId上创建一个索引

这可能吗?我尝试过不同的CREATE INDEX语法组合,但它们似乎都不支持hstore数组中的索引字段.

Dav*_*esh 5

我觉得你误解了PostgreSQL Array.一个Array实际上只是一个字符串.你不能索引HSTORE数组中的对象(在本例中是s),因为它不是a TABLE.

相反,创建一个额外的表:

CREATE TABLE customer (
    pk bigserial PRIMARY KEY,
    customer hstore
);

CREATE TABLE purchases (
    pk bigserial PRIMARY KEY,
    customer_pk bigint not null,
    purchase hstore not null,
    constraint "must be a valid customer!" 
        foreign key (customer_pk) references customer(pk)
);
Run Code Online (Sandbox Code Playgroud)

另外,你为什么在这里使用HSTOREs?

如果您必须INDEX根据"purchase" HSTORE此处创建,请执行以下操作:

CREATE OR REPLACE FUNCTION purchase_amount(purchase hstore) returns float as $$
    select ($1 -> 'price')::float;
$$ language 'SQL' IMMUTABLE;

CREATE INDEX "purchases by price" ON purchases (purchase_amount(purchase));
Run Code Online (Sandbox Code Playgroud)

这只是一个理解HSTORE类型的练习吗?或者你是否有一些真正的用例会使你对真实数据的所有混淆都值得?

  • 这不是混淆.在部署新版本的应用程序时,需要零停机升级(即我们无法使用ALTER TABLE ADD COLUMN锁定表).Hstore似乎是一个很好的选择,基本上有一个无架构的实体存储,可以通过应用程序逻辑进行超时演变而无需数据库升级 (2认同)
  • 在postgresql中向表中添加一列不会在任何明显的时间内锁定表(假设该列没有约束且可以为空). (2认同)