在 postgresql jsonb 中存储外键是个坏主意吗?

Storing foreign keys in postgresql jsonb a bad idea?

在 jsonb 列中存储外键有哪些相关问题?

上下文:

我有 table 个项目:

Item 
--------------------------
| id   | name | property |
| PK   | text |  jsonb   |

属性列为一级jsonb,结构如下:

[
  {"value": "white", "item_attribute_id": "1"},
  {"value": "71", "item_attribute_id": "3"},
  {"value": "29", "item_attribute_id": "4"},
  {"value": "48-70", "item_attribute_id": "5"},
  {"value": "190", "item_attribute_id": "6"}
]

item_attribute_id 是一个指向 table 属性的外键,它包含与给定属性(名称、类型、描述)相关的所有内容。

我找不到任何文献来说明为什么这可能是一种 good/bad 做法。是否有任何明显的直接相关问题被我忽略了?

您需要考虑以下关于 JSONB 类型的事情:

  • 查询会更复杂;如果您对此感到满意 JSONB functions (they are more about SELECT statements), UPDATE operation will still be tricky - please consider @Erwin's answer
  • 大小开销; 对于小型文档来说这并不重要,但在规模上你可能会碰壁。只需比较 pg_column_size() 个案例的结果。
  • 有限的索引支持;当您通过 elementarray 中执行搜索时,您将没有运气(json_array_elements() 等功能)。默认 GIN 索引支持使用 (CONTAINS) @>、(EXISTS)?、(EXISTS ALL)?& 和(EXISTS ANY)?| 运算符,因此您需要小心使用的查询。 jsonb 支持 btreehash 索引。您可以查看详情here.

要考虑的文章: