Mmeyer
Mmeyer

Reputation: 401

Postgresql 9.4 JSONB type, Select by date range

I'm migrating from Mongodb, and looking how select by range using jsonb type, I have ~2.880.000 records by day and I need query the database by station and date fields, I know how select by time range

SELECT * FROM stations WHERE date >= '2014-02-01' AND date <  '2014-03-01 AND station = 'AA01'

But I don't know how query the database with JSONB data type.

CREATE TABLE stations (
  id SERIAL PRIMARY KEY,
  event JSONB
);

INSERT INTO test(event) VALUES('{"station":"AA01","value":2.31,"date":"2015-01-23 18:02:48.906569865 +0000 UTC"}');
INSERT INTO test(event) VALUES('{"station":"AA02","value":4.1,"date":"2015-01-23 19:02:48.906569865 +0000 UTC"}');

Also I'm wondering how get a good performance approach, thanks.

Upvotes: 11

Views: 7498

Answers (1)

Marth
Marth

Reputation: 24812

SELECT *
FROM stations
WHERE to_date(event->>'date', 'YYYY-MM-DD') 
    BETWEEN '2014-02-01' 
    AND     '2014-03-01'
AND event->>'station' = 'AA01';

Upvotes: 22

Related Questions