如何检查 PostgreSQL 9.3 中右侧的无限范围是否为 NULL - 确保使用 GIST 索引

How to check if an unbounded range is NULL on the right in PostgreSQL 9.3 - ensuring GIST indexes are used

我在 PG 9.3 中使用范围数据类型(启用 btree_gist,但我认为这不重要)。我有包含这些范围列的 GIST 索引。有的是int8range,有的是tsrange。

我想使用 WHERE 表达式进行查询,本质上是 "range is NULL (unbounded) on the right side"。我该怎么写?

对于tsrange,我可以做到"tsrange @> timestamp 'infinity'"。但是 int8range 没有等价物。而且我认为为 int8range 正确执行此操作的方法也应该是 tsrange 的方法(不依赖于 'infinity' 的时间戳特定处理)。

该表达式应该可用于 GIST 索引(即属于这些范围类型的默认运算符 class)。

帮忙?

来自精品手册:http://www.postgresql.org/docs/9.4/static/functions-range.html

upper_inf 函数会告诉您这一点。

# select upper_inf(int8range(1, null));
 upper_inf 
-----------    
 t
(1 row)

# select upper_inf(int8range(1, 2));
 upper_inf 
-----------
 f
(1 row)

如果您需要对此进行查询,我认为索引对您没有帮助。 http://www.postgresql.org/docs/9.4/static/rangetypes.html

A GiST or SP-GiST index can accelerate queries involving these range
operators: =, &&, <@, @>, <<, >>, -|-, &<, and &> (see Table 9-47 
for more information).

您可以创建一个有助于该查询的部分索引。例如

# create table foo (id int primary key, bar int8range);  
CREATE TABLE
# create index on foo(bar) where upper_inf(bar) = true;
CREATE INDEX
# \d foo
      Table "freshop.foo"
 Column |   Type    | Modifiers 
--------+-----------+-----------
 id     | integer   | not null
 bar    | int8range | 
Indexes:
    "foo_pkey" PRIMARY KEY, btree (id)
    "foo_bar_idx" btree (bar) WHERE upper_inf(bar) = true

然后如果您将 upper_inf(bar) = true 放入查询中,优化器应该理解使用 foo_upper_inf_idx 索引。