What are the problems associated with storing foreign keys in a jsonb column?
Context:
I have a table of items:
Item
--------------------------
| id | name | property |
| PK | text | jsonb |
The property column is one-level jsonb of the following structure:
[
{"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"}
]
The item_attribute_id is a foreign key pointing to a table of attributes, which holds everything related to the given attribute (name, type, description).
I cannot find any literature on why this might be a good/bad practice. Are there any obvious directly related problems that I overlooked?
Follow these guidelines when you consider using JSON in PostgreSQL: Don't use JSON for data that can easily be stored in database tables. Avoid large JSON objects if you want to modify individual attributes. Don't use JSON if you want to use attributes in complicated WHERE conditions.
Yes, you should. Foreign keys are just constrains which helps you to make relationships and be sure that you have correct information in your database. You should use them to prevent incorrect data entry from whatsoever.
JSONB stands for “JSON Binary” or “JSON better” depending on whom you ask. It is a decomposed binary format to store JSON. JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data.
In the case of jsonb, it is comparatively faster to process the data as no reparsing is needed. JSON does not support indexing, unlike jsonb. Jsonb supports indexing to search for the keys or key/ value pairs which is a great advantage at a bigger database jsonb documents.
You need to take into consideration following things about JSONB
type:
SELECT
statements), UPDATE
operation will still be tricky - please consider @Erwin's answer regarding this.pg_column_size()
results for your case.array
by element
(functions like json_array_elements()
etc). Default GIN
index supports queries with the (CONTAINS
) @>
, (EXISTS
)?
, (EXISTS ALL
)?&
and (EXISTS ANY
)?|
operators, so you need to be careful with the queries you are using. jsonb
supports btree
and hash
indexes. You can check details here.Articles to consider:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With