jsonb_path_query Filters Documents By Path
Filter JSONB documents with jsonb_path_query and its variants, using JSONPath predicates, arrays, first matches, and bound variables.
Code
-- jsonb_path_query:用 JSONPath 表达式筛选文档中的节点
SELECT id, jsonb_path_query(payload, '$.items[*] ? (@.qty > 2)') AS hot_item
FROM carts
ORDER BY id;
-- jsonb_path_exists:判断路径是否存在,适合 WHERE 过滤
SELECT id
FROM carts
WHERE jsonb_path_exists(payload, '$.items[*] ? (@.price > 100)');
-- jsonb_path_query_array:把匹配结果聚成一个数组
SELECT
id,
jsonb_path_query_array(payload, '$.items[*].sku') AS skus
FROM carts;
-- jsonb_path_query_first:只取第一个匹配
SELECT
id,
jsonb_path_query_first(payload, '$.items[*] ? (@.qty > 2).sku') AS top_sku
FROM carts;
-- 传变量:$sku 由第三个参数提供,避免字符串拼接
SELECT
jsonb_path_query_first(payload, '$.items[*] ? (@.sku == $sku)', '{"sku": "A-1"}') AS match
FROM carts;What the code does
The file runs SELECT statements, touching carts.
Breaking the statements into their working parts: a WHERE clause limiting a statement to the rows that qualify; an ORDER BY that fixes the output order.
Applying it
The carts table is the working surface here.
Statements that matter
SELECT id
FROM carts
WHERE jsonb_path_exists(payload, '$.items[*] ? (@.price > 100)');
SELECT
jsonb_path_query_first(payload, '$.items[*] ? (@.sku == $sku)', '{"sku": "A-1"}') AS match
FROM carts;
SELECT
id,
jsonb_path_query_first(payload, '$.items[*] ? (@.qty > 2).sku') AS top_sku
FROM carts;
Interactive Tools for This Topic
JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Which tables or CTEs does it reference?
- The references are `carts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.