Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add index on jsonb field

I need to search over the values of an array key of jsonb field in Postgres.

field: {'array_key' : [1, 2, 3, 4]}

Is it possible to add index on array_key or is there any optimized method to search over the values ?

search query will be something like

select * where field['array_key'].include?(2)
like image 853
Raza Avatar asked Dec 02 '15 11:12

Raza


People also ask

Can you index Jsonb Postgres?

When we use ->> operator of JSONB, PostgreSQL can use B-tree or Hash index for processing the operations. ->> operator returns the value of the specified attribute in text format. PostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

Can we create index on JSON column in Postgres?

The answer is you can not do this. There are two types of index classes that can work on JSONB using GIST and GIN : the jsonb_path_ops , and jsonb_ops (the default). The default GIN operator class for jsonb supports queries with top-level key-exists operators ?, ?& and ?| operators and path/value-exists operator @>.

Can you index a JSON object?

You can index JSON data as you would any data of the type that you use to store it. In particular, you can use a B-tree index or a bitmap index for SQL/JSON function json_value , and you can use a bitmap index for SQL/JSON conditions is json , is not json , and json_exists .

Is Jsonb faster than JSON?

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.


1 Answers

You can create index on jsonb keys as,

add_index :table_name, :field, :using => :gin, :expression => "(field->'array_key')", :name => 'index_table_name_on_field_array_keys'

Then, you can search over indexed keys as,

where("table_name.field->'array_keys' @> ?", Array(2))
like image 133
Raza Avatar answered Sep 22 '22 03:09

Raza