其中一種可能的方式是JSONB數組。它能夠存儲任何類型的元素,它可以通過索引來提高搜索速度:
create table t as
select '["first item", 2, 3.14]'::jsonb as x
from generate_series(1,100000);
insert into t values('["second item", 3, 2.72]');
create index idx on t using gin(x);
explain analyse select * from t where x @> '3';
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ QUERY PLAN │
╞═══════════════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ Bitmap Heap Scan on t (cost=36.78..327.18 rows=100 width=47) (actual time=0.055..0.056 rows=1 loops=1) │
│ Recheck Cond: (x @> '3'::jsonb) │
│ Heap Blocks: exact=1 │
│ -> Bitmap Index Scan on idx (cost=0.00..36.75 rows=100 width=0) (actual time=0.028..0.028 rows=1 loops=1) │
│ Index Cond: (x @> '3'::jsonb) │
│ Planning time: 0.188 ms │
│ Execution time: 0.121 ms │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
explain analyse select * from t where x @> '[3, "second item"]';
┌───────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ QUERY PLAN │
╞═══════════════════════════════════════════════════════════════════════════════════════════════════════════════╡
│ Bitmap Heap Scan on t (cost=68.78..359.18 rows=100 width=47) (actual time=0.087..0.089 rows=1 loops=1) │
│ Recheck Cond: (x @> '[3, "second item"]'::jsonb) │
│ Heap Blocks: exact=1 │
│ -> Bitmap Index Scan on idx (cost=0.00..68.75 rows=100 width=0) (actual time=0.048..0.048 rows=1 loops=1) │
│ Index Cond: (x @> '[3, "second item"]'::jsonb) │
│ Planning time: 0.248 ms │
│ Execution time: 0.187 ms │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
缺點:
- 沒有準備好值使用的功能/操作來刪除元素,只能通過索引。
- 沒有現成的方法來檢查元素的唯一性,您需要自己創建它。
鏈接:
JSON Types
jsonb Indexing
JSON Functions and Operators
據最新的統計,集合所有集合有600K元素。把它分成不同的列是不可行的,是嗎? –
我看到600K行的表沒有問題。如果您擔心空間效率問題(從您的問題中不清楚),那麼我認爲您的JSON提案可能會佔用相同的空間。 – BoarGules
關於元素的數量,你有600k * distinct *元素嗎?如果沒有,並且您擔心表空間(或者想要避免冗餘),則可以在連接表中存儲一個ID列表。我第二個@BoarGules參數,如果可能的話嘗試保持SQL數據在SQL中可管理(JSON是一個PITA,但以二進制形式存儲數據是一個definitice no-go)。 – Arminius