Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 762
Mmeyer Avatar asked Jan 23 '15 20:01

Mmeyer


1 Answers

SELECT *
FROM stations
WHERE to_date(event->>'date', 'YYYY-MM-DD') 
    BETWEEN '2014-02-01' 
    AND     '2014-03-01'
AND event->>'station' = 'AA01';
like image 126
Marth Avatar answered Oct 20 '22 10:10

Marth