I have a struct/model
type User struct {
gorm.Model
Name string `gorm:"unique;not null" json:"name"`
Data postgres.Jsonb `json:"data"`
}
I can query in postgres
db=# select id,name,data from users where data @> '{"foo": "bar"}';
id | name | data
----+-------+------------------
6 | user01 | {"foo": "bar"}
7 | user02 | {"foo": "bar"}
8 | user03 | {"foo": "bar"}
How do I construct a query on the jsonB column for a particular key(s)? I was not able to find any documentation for using model objects to query. I understand its possible to do with raw query, but wanted to see how it can be done using model object ie.
users := []model.User{}
db.Find(&users, map[string]interface{}{"foo": "bar"})
http://gorm.io/docs/dialects.html
http://gorm.io/docs/query.html
The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.
The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering.
JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.
In the case of jsonb, it is comparatively faster to process the data as no reparsing is needed. JSON does not support indexing, unlike jsonb. Jsonb supports indexing to search for the keys or key/ value pairs which is a great advantage at a bigger database jsonb documents.
In your example you are not specifying which field the map will filter. Try
db.Find(&users, "data @> ?", map[string]interface{}{"foo": "bar"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With