PostgreSQL: how do I store and query JSON data efficiently?
asked 2 months ago466 viewsen
5
I have a products table where each category has different attributes (phones have ram, shoes have size). Should I use a JSONB column? How do I query it fast?
Environment:PostgreSQL 16
AI diagnosis
AI-generated. Not an answer — the community below confirms or corrects it. Always verify before relying on it.
asked 2 months ago
Grace Deroy 1.9k
1 Answer
4
✓✓ Accepted answer
JSONB is a good fit for variable attributes. Keep the common, queried-everywhere fields as real columns (name, price, category_id) and put the variable part in JSONB:
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
price_cents int NOT NULL,
attrs jsonb NOT NULL DEFAULT '{}'
);
-- containment query, uses a GIN index
CREATE INDEX products_attrs_gin ON products USING gin (attrs jsonb_path_ops);
SELECT * FROM products WHERE attrs @> '{"ram": "8GB"}';
-- a frequently filtered key: expression index
CREATE INDEX products_size_idx ON products ((attrs->>'size'));
SELECT * FROM products WHERE attrs->>'size' = '42';
Use @> (containment) to benefit from the GIN index. ->> returns text, -> returns JSON. Validate the JSON shape in your application (e.g. with zod) since the database won't enforce it.
Sign in to tell others whether this worked.
answered 2 months ago
James Étienne 2.3k
Sign in and verify your email to post an answer.