问题
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