我试图使用"新式"的JSONB类型。
我有一个名为documents
的表,其中有一个properties
字段是jsonb类型,并且其中有一个名为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
以及:
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.`
我从这篇帖子中看到 http://www.postgresql.org/message-id/10736.1409063604@sss.pgh.pa.us ,它说这应该是可能的,但我无法找出正确的语法。
当我只是简单地建立索引时:
create index test1 on documents using gin ((properties->'publication_year'));
我创建了一个索引,但是无法使用整数值查询它以获取范围,出现以下错误:
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.
任何提示和建议都非常感激。我相信其他人也会受益。TIA
publication_year
在2012年之后且在2016年之前的记录。 - Will Kessler