JSONB, arrays and full-text search
PostgreSQL isn't only rows and columns. It can store and query JSON documents, arrays and searchable text, with indexes for all of them. Many apps that think they need a separate document store or search engine are well served by Postgres alone.
json vs jsonb
json |
jsonb |
|
|---|---|---|
| Stored as | The exact text you gave it | A parsed binary format |
| Keeps whitespace, key order, duplicate keys | Yes | No |
| Fast to query and index | No | Yes |
Use jsonb. Plain json is only for keeping the exact original text.
Every editor in this lesson starts with this events table:
CREATE TABLE events (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
type text NOT NULL,
payload jsonb NOT NULL
);
INSERT INTO events (type, payload) VALUES
('signup', '{"user": {"id": 1, "name": "Asha"}, "plan": "pro", "tags": ["beta", "mobile"]}'),
('signup', '{"user": {"id": 2, "name": "Rahul"}, "plan": "free", "tags": ["web"]}'),
('purchase', '{"user": {"id": 1, "name": "Asha"}, "amount": 49.5, "items": [{"sku": "MUG", "qty": 2}]}'),
('purchase', '{"user": {"id": 3, "name": "Li"}, "amount": 899, "items": [{"sku": "LAPTOP", "qty": 1}]}');Reading values
| Operator | Returns | Example |
|---|---|---|
-> |
jsonb | payload -> 'user' |
->> |
text | payload ->> 'plan' |
#> / #>> |
jsonb / text at a path | payload #>> '{user,name}' |
->> gives text, so cast it (::numeric, ::int) before doing maths or comparisons.
Querying inside documents
Building and changing JSON
JSON to rows: JSON_TABLE
JSON_TABLE (PostgreSQL 17+, standard SQL) turns JSON into a regular table you can join and filter:
Indexing JSONB
A GIN index makes @>, ? and friends fast on millions of rows:
CREATE INDEX events_payload_idx ON events USING gin (payload);When to use JSONB (and when not)
✅ Good uses: data whose shape varies (webhook payloads, settings, form answers), and data you store and return as a whole.
❌ Not a replacement for columns: if you filter, join, or need constraints on a field, make it a real column. A common, healthy design has real columns for the important fields plus a jsonb column for the extras.
Arrays
Any type can be an array: text[], integer[]…
unnest turns an array into rows. Arrays are great for small lists like tags; for anything with its own data (a tag with a description and colour), use a separate table.
Full-text search
LIKE '%word%' is slow on large tables and dumb: it doesn't know that "running" matches "run". Postgres has a real search engine built in:
- A tsvector is a document processed into normalised words (lexemes).
- A tsquery is a search query.
@@means "matches".
Stop words like "the" and "are" are dropped, and words are reduced to their stems ("foxes" → "fox", "running" → "run").
websearch_to_tsquery accepts what users type into a search box: "exact phrase", -excluded, or. Title matches rank higher because of setweight('A'). Try searching for run.
Practice
- Find all purchase events where any item has
"sku": "MUG"(hint:payload @> '{"items": [{"sku": "MUG"}]}'). - Count how many articles have each tag.
- Search
docsfor"search engine"(with quotes, as a phrase).
1.What's the difference between -> and ->>?
2.Which should you use for most JSON columns?
3.Why is full-text search better than LIKE '%run%'?