索引postgresql数组列的大于/小于比较?

我可以在Postgresq 9.1中索引数组列来支持:

select * from t where 100 < any(a) and 100 > any(a)

其中a是一个整数数组(行数有一些值如{90,110} ,所以查询不会返回空值。)


细节

create table t ( a integer[] )
insert into t values ('{90,110}'::integer[])

对上述查询运行explain analyze ,得出:

Seq Scan on t  (cost=0.00..1.07 rows=2 width=32) (actual time=0.009..0.009 rows=1 loops=1)
  Filter: ((100 < ANY (a)) AND (100 > ANY (a)))
Total runtime: 0.023 ms

背景

以下问题描述了一种方法,但对于非固定长度数组似乎不起作用:

PostgreSQL可以索引数组列吗?

Postgres文档描述了内置的GIN操作符,但它们似乎不支持比操作更多/更少的操作:

举个例子,PostgreSQL的标准发布包含一维数组的GIN操作符类,它支持使用这些操作符的索引查询:<@,@>,=,&&


您可以在函数上创建一个索引,以int4range的形式返回列的边界:

create or replace function intarray2int4range(arr int[]) returns int4range as $$
  select int4range(min(val), max(val) + 1) from unnest(arr) as val;
$$ language sql immutable;

例:

create table t (a int[]);
insert into t
select array[i - j % 5, i - j % 3, i, i + j % 3, i + j % 5]
from generate_series(0,1000) i, generate_series(0,100) j;
create index on t using gist(a);
vacuum analyze t;

产量:

explain analyze select * from t where 20 <@ intarray2int4range(a) limit 5;
                                                               QUERY PLAN                                                               
----------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.53..16.55 rows=5 width=41) (actual time=0.056..0.060 rows=5 loops=1)
   ->  Index Scan using t_intarray2int4range_idx on t  (cost=0.53..1669.65 rows=521 width=41) (actual time=0.055..0.058 rows=5 loops=1)
         Index Cond: (20 <@ intarray2int4range(a))
 Total runtime: 0.095 ms
(4 rows)

它还允许您运行扫描值范围的类似查询:

explain analyze select * from t where '[20,30]'::int4range && intarray2int4range(a) limit 5;
                                                               QUERY PLAN                                                                
-----------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=0.53..11.82 rows=5 width=41) (actual time=0.125..0.130 rows=5 loops=1)
   ->  Index Scan using t_intarray2int4range_idx on t  (cost=0.53..3499.66 rows=1550 width=41) (actual time=0.123..0.126 rows=5 loops=1)
         Index Cond: ('[20,31)'::int4range && intarray2int4range(a))
 Total runtime: 0.169 ms
(4 rows)
链接地址: http://www.djcxy.com/p/87221.html

上一篇: Index a postgresql array column for greater than / less than comparisons?

下一篇: insensitive indexes on Postgres string array