简体   繁体   English

PostgreSQL - 查询HSTORE值的GIN索引

[英]PostgreSQL - query against GIN index of HSTORE value

I have the following constructor (as a test): 我有以下构造函数(作为测试):

CREATE TABLE product (id BIGSERIAL PRIMARY KEY, ext hstore);
CREATE INDEX ix_product_ext ON product USING GIN(ext);

INSERT
INTO    product (id, ext)
SELECT  id, ('size=>' || CEILING(10 + RANDOM() * 90) || ',mass=>' || CEILING(10 + RANDOM() * 90))::hstore
FROM    generate_series(1, 100000) id;

I have the following query, which works ok: 我有以下查询,它可以正常工作:

SELECT  COUNT(id)
FROM    (
    SELECT  id
    FROM    product
    WHERE  (ext->'size')::INT >= 41
    AND    (ext->'mass')::INT <= 20
) T

But I believe the correct way to do this is using the @> operator. 但我相信正确的方法是使用@>运算符。 I have the following, but it gives a syntax error: 我有以下内容,但它给出了语法错误:

SELECT  COUNT(id)
FROM    (
    SELECT  id
    FROM    product
    WHERE  ext @> 'size>=41,mass<=20'
) T

How should I write this? 我该怎么写呢?

Your initial attempt is correct but you need to use (partial) btree indexes and bitmap index scans to rely on it: 您的初始尝试是正确的,但您需要使用(部分)btree索引和位图索引扫描来依赖它:

create index on product(((ext->'size')::int)) where ((ext->'size') is not null);

The same for mass, and if the planner doesn't get it on the spot add two where clauses, ie where ext->'size' is not null and the same for mass. 对于质量也一样,如果规划者没有在现场得到它,则添加两个where子句,即where ext->'size' is not null且质量相同。

If there is a pattern of some kind (which is likely, since most products with a size also have a mass), potentially create a multicolumn index combining the two - one sac, the other desc. 如果存在某种模式(很可能,因为大多数具有大小的产品也具有质量),可能会创建一个多列索引,组合两个 - 一个囊,另一个desc。

The gin index as you wrote it, along with the accompanying query (with a syntax error) will basically do the same thing but unordered; 您编写的gin索引以及随附的查询(带有语法错误)基本上会执行相同的操作但无序; it'll be slower. 它会慢一些。

Reading hstore documentation your (last query) size>=41 does not mean "when size is greater or equal than 41": 读取hstore文档(最后查询) size>=41并不意味着“当大小大于或等于41时”:

text => text    make single-pair hstore

Following that you can't write mass<=20 , because there is no such operation. 之后你不能写mass<=20 ,因为没有这样的操作。 Using @> operator: 使用@>运算符:

hstore @> hstore    does left operand contain right?

you can write: 你可以写:

SELECT count(id)
FROM product
WHERE ext @> 'size=>41,mass=>20';

However it takes only these products where size is equal to 41 and mass is equal to 20. 然而,只有这些产品的尺寸等于41,质量等于20。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM