Postgresql: Query Between time range using jsonb field

3.6k views Asked by At

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.

1

There are 1 answers

4
Marth On BEST ANSWER

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