问题
I have a Postgresql 11.8 table named posts
where I would like to define a column slugs
of type JSONB, which would contain arrays of strings such as ["my-first-post", "another-slug-for-my-first-post"]
.
I can find a post having a specific slug using the ?
existence operator: SELECT * FROM posts WHERE slugs ? 'some-slug'
.
Each post is expected to only have a handful of slugs but the amount of posts is expected to grow.
Considering the above query where some-slug
could be any string:
- How can I define an index to have a reasonably performant query (no full table scan)?
- How can I ensure the same slug cannot appear multiple times (across and within the different arrays)?
I am primarily looking for a solution for Postgresql 11 but also would be interested to know solutions in future versions, if any.
The database is used in a Rails 6.0 app so I am also interested by the Rails migration syntax.
回答1:
You can support the ?
operator with a normal GIN index on the jsonb
column.
However, you cannot enforce uniqueness of array values.
Particularly if you want to have database constraints, you should not model your data using JSON. Use a regular normalized data model with several tables and foreign keys, then it will be easy to implement such an uniqueness constraint.
来源:https://stackoverflow.com/questions/63836371/indexing-postgresql-jsonb-arrays-for-element-existence-and-unicity