Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query JSONB columns with GORM using model

Tags:

go-gorm

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

like image 515
eray Avatar asked Sep 14 '18 16:09

eray


People also ask

What is the difference between JSON and Jsonb?

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.

What is a Jsonb column?

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.

Should I use Jsonb in Postgres?

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.

Is Jsonb fast?

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.


1 Answers

In your example you are not specifying which field the map will filter. Try

db.Find(&users, "data @> ?", map[string]interface{}{"foo": "bar"})
like image 135
Ezequiel Muns Avatar answered Oct 17 '22 02:10

Ezequiel Muns