简体   繁体   中英

PostgreSQL - is jsonb_set() performance O(1)?

I am building a social network, and trying to implement a data structure for saving time line event ids for each user. I was inspired by Redis Twitter Clone and its use of Redis Lists.

So for example, for user_id 45, which has in its feed the event ids: 33,55,89... we will have in Redis key:45,value: List with(33,55,89...)

I want to have a similar model in PostgreSQL. I've created a table with columns:
user_id:bigint and event_ids:jsonb. So my table will look like:

45, [33,55,89...]

So the commands I need:

UPDATE timeline_for_user 
    SET event_ids = jsonb_set(event_ids, '{0}', EVENT_ID, true);  

This puts EVENT_ID at the start of the array (index 0).

My first question: does this update happen "in place" with O(1) time? Meaning, the whole array won't be read to memory first?

Another command I need is to paginate ids from the array like so:

select jsonb_array_elements(event_ids) 
from timeline_for_user 
where user_id=55
OFFSET 10
limit 10    
  1. Is the whole array is read to memory here?

  2. Regarding the two other questions, when looking at a scenario of a fairly busy social site, with, lets say, about 1000 ids in the array, and lots of inserts and queries, will this solutions hold up? Have anyone experienced with this scenario or a similar one?

Using JSONB is unnecessary here, Postgres has arrays . For fixed size data like integers the performance of arrays will be O(1) . So you'd declare the event as integer[] .

But able relationships are what SQL databases are centered around. Instead, consider making a join table for your user's events.

create table user_events (
    user_id integer references users(id),
    event_id integer references events(id),
    created_at datetime
);

create index on user_events (datetime);

Now you can paginate them.

select event_ids
from user_events
where user_id=55
order by created_at
offset 10
limit 10 

Which will perform better, I'm not sure. You'll have to do some testing. But the index is critically important to getting good performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM