PostgreSQL: how do I store and query JSON data efficiently?

posée 2 months ago466 vuesen

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?

Environnement :PostgreSQL 16

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

1 réponse

4
✓
✓ Réponse acceptée

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.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.