问题
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)
回答1:
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))
回答2:
given that you have a 'pictures' table with a 'metadata' jsonb column
add_index(
:pictures,
"(metadata->>'Year')",
name: "index_pictures_on_metadata_year"
)
should output something like
CREATE INDEX "index_pictures_on_metadata_year" ON "pictures" ((metadata->>'Year'))
来源:https://stackoverflow.com/questions/34041821/add-index-on-jsonb-field