I'm preparing to use PostgreSQL's json storage and querying functionality. I think I understand the insert and query part somewhat, but I cannot find an example of how to support (through an index) a query into json path that is more than one level deep. I'm testing with the following:
CREATE TABLE orders (
id serial NOT NULL PRIMARY KEY,
info json NOT NULL
);
INSERT INTO orders (info)
VALUES('{ "customer": "Mark Stevens", "items": {"product": { "name" : "Phone","qty": 3}}}'),
('{ "customer": "Josh William", "items": {"product": { "name" : "Toy Car","qty": 1}}}'),
('{ "customer": "Mary Clark", "items": {"product": { "name" : "Toy Train","qty": 2}}}');
It's a bit of a constructed example. The essence is that the qty field is nested more than one level deep.
I can execute a query on this looking for all records with qty 1:
SELECT * FROM orders
WHERE info::jsonb @@ '$.items.product.qty == 1';
This all works fine. Tested using PgAdmin. So, now I want to define an index to support that query (or a version of it that can be supported by an index, as often the way you write the query matters).
I have been looking around here, and in the pg documentation, but did not see an example of an index definition that I could turn into a working one for this example. All examples seem to cover paths of only one level. for example, if qty had been one level deep into the json, the supporting index would have looked something like this
CREATE INDEX orders_index ON orders (((info ->> 'customer')::VARCHAR), ((info #>> '{items, qty}')::INTEGER));
So, my question is: Is it possible to come up with an index supporting my query into deeper json levels? And if yes, can someone provide me with an example?