From: Andrew Gierth <andrew@tao11.riddles.org.uk>
To: Johann Spies <johann.spies@gmail.com>
Cc: pgsql-general\@postgresql.org <pgsql-general@postgresql.org>
Subject: Re: How to build a btree index with integer values on jsonb data?
Date: Thu, 13 Dec 2018 09:03:02 +0000
Message-ID: <87va3x24c4.fsf@news-spur.riddles.org.uk> (raw)
In-Reply-To: <CAGZ55DSm4kGiBSJaPtTk6L7hp6xDFKaKThDLmXd_4cCFFFJe5Q@mail.gmail.com>
References: <CAGZ55DSm4kGiBSJaPtTk6L7hp6xDFKaKThDLmXd_4cCFFFJe5Q@mail.gmail.com>
>>>>> "Johann" == Johann Spies <johann.spies@gmail.com> writes:
Johann> How can I transform the following definition to index pubyear
Johann> as integer and not text?
Johann> CREATE INDEX pubyear_idx
Johann> ON some_table_where_data_field_is_of_type_jsonb USING btree
Johann> ((((((data -> 'REC'::text) -> 'static_data'::text) ->
Johann> 'summary'::text) -> 'pub_info'::text) ->> '@pubyear'::text) COLLATE
Johann> pg_catalog."default");
Johann> While I can cast the value in a SELECT statement to integer I
Johann> have been able to do the same while creating the index.
Laurenz' answer was almost correct, just got the position of the parens
wrong.
When you use an expression in an index, the outermost level of the
expression must either be (syntactically) a function call, or it must
have parens around its _outermost_ level.
You can simplify selecting from nested json using #>> in place of the ->
and ->> operators. (x #>> array['foo','bar']) is equivalent to doing
((x -> 'foo') ->> 'bar')
So:
CREATE INDEX pubyear_idx
ON some_table_where_data_field_is_of_type_jsonb USING btree
(
((data #>> array['REC','static_data','summary','pub_info','@pubyear'])::integer)
);
Note the ::integer is inside the parens that define the column value
within the outermost ( ) which enclose the column _list_.
--
Andrew (irc:RhodiumToad)
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: andrew@tao11.riddles.org.uk, johann.spies@gmail.com
Subject: Re: How to build a btree index with integer values on jsonb data?
In-Reply-To: <87va3x24c4.fsf@news-spur.riddles.org.uk>
References: <CAGZ55DSm4kGiBSJaPtTk6L7hp6xDFKaKThDLmXd_4cCFFFJe5Q@mail.gmail.com> <87va3x24c4.fsf@news-spur.riddles.org.uk>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox