如何索引jsonb整数值

Wil*_*ler 9 postgresql indexing gwt-gin jsonb

我正在尝试使用"newish"JSONB类型.

我有一个documents带有propertiesjsonb字段的表,在那里是一个字段publication_year.我想查找一年范围内的所有文件记录,例如2013-2015. [编辑:查询一系列值是这里的主要挑战,即使我使用了下面的完全匹配示例.请求的方法也适用于美元范围(价格> 20美元,价格<40美元)或时间戳范围).

我试过了:

create index test1 on documents using gin ((cast(properties->'announced_on_year' as integer)));

ERROR:  cannot cast type jsonb to integer
Run Code Online (Sandbox Code Playgroud)

以及:

create index test1 on documents using gin (cast(properties->>'publication_year' as integer));

ERROR:  data type integer has no default operator class for access method "gin"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.`
Run Code Online (Sandbox Code Playgroud)

我从这篇文章中看到http://www.postgresql.org/message-id/10736.1409063604@sss.pgh.pa.us这应该是可能的,但我无法弄清楚正确的语法.

当我只做一个简单的索引:

create index test1 on documents using gin ((properties->'publication_year'));
Run Code Online (Sandbox Code Playgroud)

它创建了一个索引,但是我无法使用整数值来查询它以获得范围

select count(*) from documents where properties->>'publication_year' = 2015;
ERROR:  operator does not exist: text = integer
LINE 1: ...*) from documents where properties->>'publication_year' = 2015;
                              ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
Run Code Online (Sandbox Code Playgroud)

任何提示和提示高度赞赏.我相信别人也会受益.TIA

qwe*_*rty 5

根据我的经验,我发现在 JSONB 列上使用 GIN 索引并不快。您可以通过将其转换为整数来创建普通索引

CREATE INDEX test1 ON documents ((properties->>'publication_year')::int);
Run Code Online (Sandbox Code Playgroud)

此外,GIN 有一些限制在创建之前应考虑。即使索引整个 JSONB 列也可能导致大量表大小的索引。

这是基于我的经验和查看 Postgres 文档。


mur*_*son 1

为什么不按照文档中的描述为整个jsonb字段定义一个索引?

create index test1 on documents using gin (properties);
Run Code Online (Sandbox Code Playgroud)