0

This is my column:

[
  { id: 1, value: 1, complete: true }, 
  { id: 2, value: 1, complete: false },
  { id: 3, value: 1, complete: true } 
]

First, is there a "correct" way to work with a jsonb scheme? should I redesign to work with a single json instead of the array of hashes?

I have about 200 entries on the database, the column status has 200 of those itens.

  • How would I perform a query to get the count of true/false?
  • How can I query for ALL complete itens? I can query for the database rows in which the json has an item complete, but I can't query for all the itens, in all rows of the database that are complete.

Appreciate the help, thank you

3
  • There's all kinds of ways of interacting with it. Commented Apr 18, 2021 at 1:48
  • Your schema seems to be fixed. So the best thing would be not to use JSON at all but simple relational means. Best in terms of working with the data in SQL at least. Commented Apr 18, 2021 at 1:52
  • @tadman if that's going to be the help, would you please point to me where I can select inside the array of hashes into this documentation? I've spent hours on that document before asking the question, another set of hours after. Maybe I'm just overly blind on this, but I can't find it. Commented Apr 18, 2021 at 12:55

1 Answer 1

1

Aha! I found it here:

https://levelup.gitconnected.com/how-to-query-a-json-array-of-objects-as-a-recordset-in-postgresql-a81acec9fbc5

Say your dataset is like this:

[{
  "productid": "3",
  "name": "Virtual Keyboard",
  "price": "150.00"
}, {
  "productid": "1",
  "name": "Dell 123 Laptop Computer",
  "price": "1300.00"
},
{
  "productid": "8",
  "name": "LG Ultrawide Monitor",
  "price": "190.00"
}]

The proper way to count it, is like this:

select items.name, count(*) as num from 
purchases,jsonb_to_recordset(purchases.items_purchased) as items(name text)
group by items.name
order by num Desc

Works like a charm and is extremely fast. To do it in Rails, you need to use Model.find_by_sql(....) and indicate your select therem. I'm sure there are probably better ways to do it.

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.