Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
904 views
in Technique[技术] by (71.8m points)

postgresql - jsonb vs jsonb[] for multiple addresses for a customer

It's a good idea to save multiple addresses in a jsonb field in PostgreSQL. I'm new in nosql and I'd like to test PostgreSQL to do that. I don't want to have another table with addresses, I prefer to have it in the same table. But I'm in doubt, I've seen PostreSQL have jsonb and jsonb[].

Which one is better to store multiple addresses? If I use jsonb, I think I must to add a prefix for every field like this:

"1_adresse_line-1"
"1_adresse_line-2"
"1_postalcode"

"2_adresse_line-1"
"2_adresse_line-2"
"2_postalcode"

"3_adresse_line-1"
"3_adresse_line-2"
"3_postalcode"

etc.

Is it better to use jsonb[], how does it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use a jsonb (not jsonb[]!) column with the structure like this:

select
'[{
        "adresse_line-1": "a11",
        "adresse_line-2": "a12",
        "postalcode": "code1"
    },
    {
        "adresse_line-1": "a21",
        "adresse_line-2": "a22",
        "postalcode": "code2"
    }
]'::jsonb;

Though, a regular table related to the main one is a better option.

Why not jsonb[]? Take a look at JSON definition:

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

In a jsonb column you can therefore store an array of objects. Attempts to use the array of jsonb are probably due to misunderstanding of this type of data. I have never seen a reasonable need for such a solution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...