I'll help design an efficient column store compression system using PostgreSQL arrays and ranges. Let's break this down into several parts:
- First, let's create a table structure that supports efficient compression and querying:
-- Create a table to store our columnar data
CREATE TABLE columnar_store (
chunk_id bigint PRIMARY KEY,
time_range tstzrange, -- Store time range for this chunk
value_stats jsonb, -- Store min/max/avg for numeric columns
-- Arrays sized for TOAST compression (>2KB)
id_array bigint[] NOT NULL,
timestamp_array timestamptz[] NOT NULL,
value_array numeric[] NOT NULL,
text_array text[] NOT NULL,
-- Bitmap for deletion tracking
deletion_bitmap bit varying
);
-- Create indexes for efficient querying
CREATE INDEX idx_time_range ON columnar_store USING gist (time_range);
CREATE INDEX idx_value_stats ON columnar_store USING gin (value_stats);
- Let's create a function to insert data in chunks:
CREATE OR REPLACE FUNCTION insert_columnar_chunk(
source_data_sql text,
chunk_size int DEFAULT 1000
) RETURNS void AS $$
DECLARE
next_chunk_id bigint;
BEGIN
-- Get next chunk ID
SELECT COALESCE(MAX(chunk_id) + 1, 1) INTO next_chunk_id FROM columnar_store;
-- Insert data in columnar format
EXECUTE format(
'WITH chunk_data AS (
SELECT array_agg(id) AS id_array,
array_agg(timestamp_col) AS timestamp_array,
array_agg(value_col) AS value_array,
array_agg(text_col) AS text_array
FROM (%s) src
)
INSERT INTO columnar_store (
chunk_id,
time_range,
value_stats,
id_array,
timestamp_array,
value_array,
text_array,
deletion_bitmap
)
SELECT
%L,
tstzrange(min(timestamp_col), max(timestamp_col), ''[]''),
jsonb_build_object(
''min_value'', min(value_col),
''max_value'', max(value_col),
''avg_value'', avg(value_col)
),
id_array,
timestamp_array,
value_array,
text_array,
NULL
FROM (%s) src, chunk_data',
source_data_sql,
next_chunk_id,
source_data_sql
);
END;
$$ LANGUAGE plpgsql;
- Here's how to query the data efficiently:
-- Query for a specific time range with value filtering
CREATE OR REPLACE FUNCTION query_columnar_data(
start_time timestamptz,
end_time timestamptz,
min_value numeric DEFAULT NULL,
max_value numeric DEFAULT NULL
) RETURNS TABLE (
id bigint,
ts timestamptz,
val numeric,
txt text
) AS $$
BEGIN
RETURN QUERY
WITH matching_chunks AS (
SELECT chunk_id,
id_array,
timestamp_array,
value_array,
text_array,
deletion_bitmap
FROM columnar_store
WHERE time_range && tstzrange(start_time, end_time, '[]')
AND (min_value IS NULL OR (value_stats->>'max_value')::numeric >= min_value)
AND (max_value IS NULL OR (value_stats->>'min_value')::numeric <= max_value)
),
unnested AS (
SELECT
chunk_id,
unnest(id_array) AS id,
unnest(timestamp_array) AS ts,
unnest(value_array) AS val,
unnest(text_array) AS txt,
generate_subscripts(id_array, 1) AS array_index
FROM matching_chunks
)
SELECT id, ts, val, txt
FROM unnested
WHERE ts BETWEEN start_time AND end_time
AND (min_value IS NULL OR val >= min_value)
AND (max_value IS NULL OR val <= max_value)
AND (deletion_bitmap IS NULL OR
NOT get_bit(deletion_bitmap, array_index - 1));
END;
$$ LANGUAGE plpgsql;
- For updates and deletes:
-- Soft delete function
CREATE OR REPLACE FUNCTION soft_delete_columnar_data(
p_chunk_id bigint,
p_array_indexes int[]
) RETURNS void AS $$
BEGIN
-- Initialize deletion bitmap if NULL
UPDATE columnar_store
SET deletion_bitmap = COALESCE(deletion_bitmap,
set_bit(cast(repeat('0', array_length(id_array, 1)) as bit varying), 0, 0))
WHERE chunk_id = p_chunk_id;
-- Set deletion bits
UPDATE columnar_store
SET deletion_bitmap = (
SELECT array_reduce(p_array_indexes,
(acc, idx) -> set_bit(acc, idx - 1, 1),
deletion_bitmap)
)
WHERE chunk_id = p_chunk_id;
END;
$$ LANGUAGE plpgsql;
-- Update function (creates new version in new chunk)
CREATE OR REPLACE FUNCTION update_columnar_data(
p_chunk_id bigint,
p_array_index int,
p_new_value numeric,
p_new_text text
) RETURNS void AS $$
DECLARE
new_chunk_id bigint;
BEGIN
-- Mark old record as deleted
PERFORM soft_delete_columnar_data(p_chunk_id, ARRAY[p_array_index]);
-- Insert updated record in new chunk
SELECT COALESCE(MAX(chunk_id) + 1, 1) INTO new_chunk_id FROM columnar_store;
INSERT INTO columnar_store (
chunk_id,
time_range,
value_stats,
id_array,
timestamp_array,
value_array,
text_array
)
SELECT
new_chunk_id,
tstzrange(timestamp_array[p_array_index], timestamp_array[p_array_index], '[]'),
jsonb_build_object(
'min_value', p_new_value,
'max_value', p_new_value,
'avg_value', p_new_value
),
ARRAY[id_array[p_array_index]],
ARRAY[timestamp_array[p_array_index]],
ARRAY[p_new_value],
ARRAY[p_new_text]
FROM columnar_store
WHERE chunk_id = p_chunk_id;
END;
$$ LANGUAGE plpgsql;
Key optimization points:
-
Chunk size: Choose a chunk size that results in arrays larger than 2KB to trigger TOAST compression but small enough for efficient querying (typically 1000-10000 records)
-
Statistics: The value_stats JSONB field enables quick filtering without scanning arrays
-
Time range: Using tstzrange with GiST index enables efficient time-based queries
-
Soft deletes: Using a bitmap for deletions is more space-efficient than array filtering
-
Updates: Creating new chunks for updates maintains data integrity while allowing efficient querying
-
Compression: TOAST compression will automatically kick in for large arrays
To further optimize:
-
Consider partitioning the columnar_store table by time range for better query performance
-
Add additional statistics as needed for your specific query patterns
-
Implement periodic chunk consolidation to merge partially empty chunks
-
Consider using int[] instead of bigint[] if your IDs fit within integer range
-
Use UNLOGGED tables if WAL logging isn't required
-
Consider using parallel query execution for large scans
Example usage:
-- Insert test data
SELECT insert_columnar_chunk(
'SELECT generate_series(1,1000) as id,
now() + (interval ''1 minute'' * generate_series(1,1000)) as timestamp_col,
random() * 100 as value_col,
md5(random()::text) as text_col'
);
-- Query data
SELECT * FROM query_columnar_data(
now(),
now() + interval '1 day',
50,
100
);
-- Soft delete some records
SELECT soft_delete_columnar_data(1, ARRAY[1,2,3,4,5]);
-- Update a record
SELECT update_columnar_data(1, 10, 99.99, 'updated text');