Best Way to Index All JSONB Fields With Boolean Values in PostgreSQL

坚强是说给别人听的谎言 提交于 2020-01-25 06:54:08

问题


I am creating a table that has a features jsonb column. There will be a dynamic set of features (each row can have an unknown set of features). Each feature is boolean true/false values.

Example:

  • Row 1: feature: { "happy": true, "tall": false, "motivated": true }
  • Row 2: feature: { "happy": true, "fast": true, "strong": false }
  • Row 3: feature: { "smart": true, "fast": true, "sleepy": false }

What would be the best way to index this column such that I can make queries to find all rows with featureX = true? All the examples I have looked up seem to need a field name to base the index on.


回答1:


You can create an index on the complete JSON value:

create index on the_table using gin (features);

It can be used for e.g. the @> operator:

select *
from the_table
where features @> '{"happy": true}'

Another method would be to not store key/value pairs, but only list the features that are "true" in an array: ["happy", "motivated"] and then use the ? operator. This way the JSON value is a bit smaller and that might be more efficient.

select *
from the_table
where features ? 'happy'

or if you want to test for multiple features:

select *
from the_table
where features ?| array['happy', 'motivated']

That too can make use of the GIN index



来源:https://stackoverflow.com/questions/58759162/best-way-to-index-all-jsonb-fields-with-boolean-values-in-postgresql

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