Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: Query Between time range using jsonb field

I have a table with two fields:

id(serial), data(jsonb)

And into data I have records with a Datetime field stored as UNIX timestamps:

{"Device":132,"Datetime": 1434166552,...}

I'm trying to query between ranges:

SELECT *
FROM trips
WHERE data->>'Datetime' BETWEEN
    EXTRACT(EPOCH FROM date '2014-04-01') AND
    EXTRACT(EPOCH FROM date '2014-04-15' + interval '1 day')
    AND id = 123

Message

ERROR:  operator does not exist: text >= double precision
LINE 3: WHERE data->>'Datetime' BETWEEN

Something I'm doing wrong, please cloud somebody help me? Thanks.

like image 299
Goku Avatar asked Jun 15 '15 00:06

Goku


People also ask

How do I query Jsonb data?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

Is Postgres Jsonb fast?

Speed. Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record.

Is Jsonb better than JSON?

The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.


1 Answers

The ->> operator returns an JSON object field as text (see here). You need to cast it :

SELECT *
FROM trips
WHERE (data->>'Datetime')::int 
  BETWEEN EXTRACT(EPOCH FROM date '2014-04-01') 
      AND EXTRACT(EPOCH FROM date '2014-04-15' + interval '1 day')
  AND id = 123
like image 123
Marth Avatar answered Oct 07 '22 20:10

Marth