Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query nested jsonb Postgres column

I have a metadata column of type jsonb.

I know how to check whether it contains a specific key:

obj = Model.create
obj.metadata = {"foo"=>"1", "bar"=>{"baz"=>{"qux"=>2}}}

Model.where("(metadata->'bar') IS NOT NULL") # returns obj

I wonder, how would I check if there is baz key in obj.metadata['bar'] and, if I had, for deeper nested keys?

like image 886
Andrey Deineko Avatar asked Sep 20 '16 13:09

Andrey Deineko


People also ask

How do I query Jsonb data in PostgreSQL?

Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

Is Postgres Jsonb fast?

Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record. The reduced disk load speeds up overall performance. Support for indexing.

Is Jsonb faster than JSON?

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.


1 Answers

Ok, just found a way:

Model.where("(metadata -> 'bar' ->> 'baz') IS NOT NULL")

if metadata has more nested json:

obj.metadata = {"foo"=>"1", "bar"=>{"baz"=>{"qux"=>2}}}

and I would want to see, if there's metadata['bar']['baz']['qux']:

Model.where("(metadata -> 'bar' -> 'baz' ->> 'qux') IS NOT NULL")
like image 161
Andrey Deineko Avatar answered Sep 20 '22 02:09

Andrey Deineko