2

I have a JSON object stored as JSONB in my Postgres database under the column name cart. This is the cart data for 2 users

"items": [
 {
   "name": "T-shirt",
   "price": 250,
   "item_id": 111,
   "quantity": 1
 },
 {
   "name": "Trousers",
   "price": 600,
   "item_id": 222,
   "quantity": 1
 }
]
}

&&&&

{
"items": [
 {
   "name": "Jeans",
   "price": 250,
   "item_id": 333,
   "quantity": 1
 },
 {
   "name": "Trousers",
   "price": 600,
   "item_id": 444,
   "quantity": 1
 }
]
}


This data is stored under The column name cart. I tried using Gin indexes but wasn't clear about what i was doing. How should i be able to query The data such that i can find the list of all users that have trousers as an item in their cart in Postgres? Also, i am New to this implementation and keen to learn So Would be helpful If the implementations are made through Golang.
Thanks, Pushkar Singh

1 Answer 1

3
USING gin ((cart->'items') jsonb_path_ops);

SELECT * FROM order2 WHERE cart->'items' @> '[{"name":"Trousers"}]';

Refrences :

Query for array elements inside JSON type

Index for finding an element in a JSON array

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.