Indexing Postgresql JSONB arrays for element existence and unicity

与世无争的帅哥 提交于 2021-01-29 18:37:12

问题


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

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