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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which tables or CTEs does it reference?
The references are `carts`.