2012-03-19 115 views
9

hstore文檔僅討論一次使用「插入」hstore一行的方式。 有沒有辦法批量上傳幾個100k行 ,這可能是兆字節或千兆到一個postgres hstore。將大量數據加載到Postgres Hstore

複製命令似乎只上傳CSV文件列

可能有人張貼一個例子工作?最好是使用Python/psycopg

回答

3

都插入工作和複製的解決方案出現在自然的方式來爲我工作

create table b(h hstore); 
insert into b(h) VALUES ('a=>1,b=>2'::hstore), ('c=>2,d=>3'::hstore); 
select * from b; 
     h   
-------------------- 
"a"=>"1", "b"=>"2" 
"c"=>"2", "d"=>"3" 
(2 rows) 

$ cat > /tmp/t.tsv 
a=>1,b=>2 
c=>2,d=>3 
^d 

copy b(h) from '/tmp/t.tsv'; 
select * from b; 
     h   
-------------------- 
"a"=>"1", "b"=>"2" 
"c"=>"2", "d"=>"3" 
"a"=>"1", "b"=>"2" 
"c"=>"2", "d"=>"3" 
(4 rows) 
5

以上的答案,如果你嘗試在多列複製包括列似乎不完整與hstore類型,並使用逗號分隔符,COPY迷糊,如:

$ cat test 
1,a=>1,b=>2,a 
2,c=>3,d=>4,b 
3,e=>5,f=>6,c 

create table b(a int4, h hstore, c varchar(10)); 
CREATE TABLE; 
copy b(a,h,c) from 'test' CSV; 
ERROR: extra data after last expected column 
CONTEXT: COPY b, line 1: "1,a=>1,b=>2,a" 

類似地:

copy b(a,h,c) from 'test' DELIMITER ','; 
ERROR: extra data after last expected column 
CONTEXT: COPY b, line 1: "1,a=>1,b=>2,a" 

這可以是固定的,但是,通過導入爲CSV和引用領域導入hstore:

$ cat test 
1,"a=>1,b=>2",a 
2,"c=>3,d=>4",b 
3,"e=>5,f=>6",c 

copy b(a,h,c) from 'test' CSV; 
COPY 3 
select h from b; 
     h   
-------------------- 
"a"=>"1", "b"=>"2" 
"c"=>"3", "d"=>"4" 
"e"=>"5", "f"=>"6" 
(3 rows) 

報價僅在CSV格式允許的,所以導入爲CSV是必需的,但你可以使用DELIMITER和QUOTE參數爲COPY顯式設置字段分隔符和引號字符爲非','和'「'值。

0

你可以使用copy binary命令來做到這一點。

我不知道可以做到這一點的Python庫,但我有一個可以幫助您瞭解列編碼的紅寶石。

https://github.com/pbrumm/pg_data_encoder