2017-04-24 211 views
0

有一個表像以下:Postgres的:在陣列型的JSON字段設置唯一索引

CREATE TABLE test (my_field jsonb NOT NULL) 

my_field具有像collection其存儲在varchar[]格式值的鍵:

{my_field: {collection: ['a', 'b', 'c']}} 

我知道可以爲簡單的json值設置唯一的索引。例如,對於{my_field: {name: 'Someone'}},可以設置唯一約束。 (已經試過了)

我已經嘗試過exclude using gist很多,但到目前爲止我一無所獲。

在這種情況下可以設置唯一的(考慮重疊)約束嗎?

在此先感謝。

+0

你想有一個英國OFR陣列..下令或不.. [ '一', 'B'] <> [? 'b','a']?.. –

+0

這不是訂貨的問題,唯一性是我在尋找的東西。 – Kaveh

回答

0

如果沒有關係,然後訂購的簡單指標將工作:

so=# CREATE TABLE test (my_field jsonb NOT NULL); 
CREATE TABLE 
so=# insert into test select '{"my_field": {"collection": ["a", "b", "c"]}}'; 
INSERT 0 1 
so=# create unique index uk_c on test ((my_field->'my_field'->>'collection')); 
CREATE INDEX 
so=# insert into test select '{"my_field": {"collection": ["a", "b", "c"]}}'; 
ERROR: duplicate key value violates unique constraint "uk_c" 
DETAIL: Key (((my_field -> 'my_field'::text) ->> 'collection'::text))=(["a", "b", "c"]) already exists. 
+0

如果我只插入[「a」,「b」]會怎麼樣? – Kaveh

+0

我需要重疊的東西(&&)。我很感謝你關心的人。 – Kaveh