jsonb_path_exists tests whether a JSON path produces at least one value for a jsonb column. A true result keeps the current SQL row. section 5.4.4
Find pizzas containing Parmesan
Filter cheese objects with `$.toppings.cheese[*] ? (exists(@.parmesan))`. The path visits every cheese, while `@` represents the current cheese object. Grouping the matching rows by pizza type returns three cheese and custom pizzas. section 5.4.4
Listing 5.9 Using filters in path expressions
SELECT
count(*) AS total_cnt,
pizza->'type' as pizza_type
FROM pizzeria.order_items
WHERE jsonb_path_exists(pizza,
'$.toppings.cheese[*] ? (exists(@.parmesan))')
GROUP BY pizza_type
ORDER BY total_cnt DESC;
Run the complete filter query against pizzeria.order_items and compare its grouped counts with the supplied output. section 5.4.4
Listing 5.10 Chaining multiple filter expressions
SELECT count(*)
FROM pizzeria.order_items
WHERE jsonb_path_exists(
pizza,
'$ ? (@.type == "custom") .toppings.cheese[*].parmesan ? (@ == "extra")'
);
Explore chained filters that first select custom pizzas and then require Parmesan marked as extra. section 5.4.4
