add index on jsonb field

旧时模样 提交于 2019-12-04 09:14:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!