|
| 1 | +\c pg_features_demo |
| 2 | +SET ROLE TO demorole; |
| 3 | + |
| 4 | +/* |
| 5 | +
|
| 6 | +HASH partitioning, available from v11, differentiates quite a lot from LIST and RANGE methods and in short takes care of |
| 7 | +even distribution of data for us - we just say how many sub-partitions we need (need to pre-create these as with other |
| 8 | +partitioning types) and which column will be used for calculating the hash which then will be used to choose the partition |
| 9 | +where some row will land. |
| 10 | +
|
| 11 | +Hash partitioning is especially suited for "key-value" or "NoSQL" use cases and it helps to increase query throughput a |
| 12 | +lot as user CRUD will be more parallel / contention free and also many background Autovacuum processes can work on the |
| 13 | +table simultaneously. Also you can use Postgres safeguarded real primary keys with hashing without problems which is problematic |
| 14 | +with other partitioning types. |
| 15 | +
|
| 16 | +*/ |
| 17 | + |
| 18 | +-- the "main" or "parent" table that users will be interacting with |
| 19 | +CREATE TABLE web_sessions ( |
| 20 | + session_id uuid NOT NULL PRIMARY KEY, |
| 21 | + -- data columns ... |
| 22 | + created_on timestamptz NOT NULL DEFAULT now(), |
| 23 | + last_modified_on timestamptz, |
| 24 | + session_data jsonb |
| 25 | + |
| 26 | +) PARTITION BY HASH (session_id); |
| 27 | + |
| 28 | +-- partition to hold data for year 2019 |
| 29 | +CREATE TABLE web_sessions_0 PARTITION OF web_sessions FOR VALUES WITH (MODULUS 4, REMAINDER 0); |
| 30 | +CREATE TABLE web_sessions_1 PARTITION OF web_sessions FOR VALUES WITH (MODULUS 4, REMAINDER 1); |
| 31 | +CREATE TABLE web_sessions_2 PARTITION OF web_sessions FOR VALUES WITH (MODULUS 4, REMAINDER 2); |
| 32 | +CREATE TABLE web_sessions_3 PARTITION OF web_sessions FOR VALUES WITH (MODULUS 4, REMAINDER 3); |
| 33 | + |
| 34 | +-- we keep working with the "main" table ... |
| 35 | +INSERT INTO web_sessions(session_id, session_data) |
| 36 | + SELECT 'a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11', '{"auth_token": "eeshu8tiiChe4AeP4junaiyie7thewu5"}'; |
| 37 | + |
| 38 | +SELECT * FROM web_sessions; -- 1 row |
| 39 | + |
| 40 | +-- if you want to disable implicit scanning of sub-tables one can use the ONLY keyword |
| 41 | +SELECT * FROM ONLY web_sessions; -- 0 rows |
0 commit comments