Skip to content
Advertisement

Ideal Postgres Index For Json Data With Integer Timestamp

I have millions of records in this table using Amazon Aurora Postgres 10.7:

Example row:

{"id": "abc", "ts": 1580879910, "data": "my stuff"}

I have these queries that take dozens of seconds:

I’m trying to improve performance here, and these are all the indexes that I tried, but at most I get an INDEX SCAN in the query plan at best.

I adjust my queries as well to: ORDER BY (jsonData->>'ts')::integer, but nothing.

Best plan:

Can anyone recommend a way to adjust the indexes or queries for these to become faster? Thanks!

Advertisement

Answer

Using OFFSET like this will always cause bad performance.

You should use keyset pagination:

Create this index:

Then, to paginate, your first query is:

Remember jsonData->>'ts' and id from the last result row you got in last_ts and last_id.

Your next page is found with

Keep going like this, and retrieving the 500th page will be as fast as retrieving the first.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement