2011-12-18 89 views
2

我有表模式:PostgreSQL的:如何高效填入表10個百萬行與隨機字符串

test1 (id integer primary key , padding text) 

(有指數ID),我想有10個百萬行與

隨機填充(填充長度小於1024的符號)。 如何快速生成並將其插入表中?

我想現在該解決方案:

insert into test1 (select *, random_string(1024) from generate_series(0, 10000000)); 

其中random_string是一個函數:

create or replace function random_string(length integer) returns text as 
$$ 
declare 
    chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}'; 
    result text := ''; 
    i integer := 0; 
    length2 integer := (select trunc(random() * length + 1)); 
begin 
    if length2 < 0 then 
    raise exception 'Given length cannot be less than 0'; 
    end if; 
    for i in 1..length2 loop 
    result := result || chars[1+random()*(array_length(chars, 1)-1)]; 
    end loop; 
    return result; 
end; 
$$ language plpgsql; 

看來,PostgreSQL是創建臨時表,該臨時表的只有發電將採取2小時。

+0

你希望每一個這樣的字符串都是1024個字符嗎? – 2011-12-18 18:03:15

+0

@Catcall:顯然不是,因爲'length2'設置爲'trunc(random()* length + 1)'。 – ruakh 2011-12-18 18:36:38

+0

@ruakh:我讀了代碼的功能。我還讀到「填充長度小於1024的符號」,這可能意味着「填充字符串短於1024字節(或字符,不一定是相同的)到1024字節(或字符)。 – 2011-12-18 22:22:59

回答

5

如果效率是一個高度關注的問題,那麼使用不同的語言來生成數據會更有意義,這種語言會更仔細地優化,然後使用語句將數據複製到表中。例如,如果你是一個Linux-y座標系上,你可以將此C99程序保存爲generate_test1_data.c

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


#define MIN_ID 0 
#define MAX_ID 10000000 

#define MAX_LEN 1024 

#define CHARS "" \ 
       "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ 
       "abcdefghijklmnopqrstuvwxyz" 


int main() 
{ 
    char const * const chars = CHARS; 
    int const num_chars = strlen(chars); 

    printf("COPY test1 FROM STDIN;\n"); 

    for(int i = MIN_ID; i <= MAX_ID; ++i) 
    { 
     printf("%d\t", i); // can be optimized if needed 
     int const len = rand() % MAX_LEN + 1; 
     for(int j = 0; j < len; ++j) 
      putchar(chars[rand() % num_chars]); 
     putchar('\n'); 
    } 

    printf("\\.\n"); 
    return 0; 
} 

,然後運行以下命令:

gcc -std=c99 -Wall generate_test1_data.c -o generate_test1_data 
./generate_test1_data > populate_test1.sql 
psql -U ... -d ... -f populate_test1.sql 

在一個發展箱,我有這一點很方便,整個過程需要十分鐘以上的時間(或者至少我在一百分之一的數據上進行了試驗,而這一點在6秒之內就完成了)。這是一個非常強大的框,所以在你的系統上可能需要的時間比—甚至更​​多更多更長—但是,我認爲,幾乎不會像現在的方法那麼長。

+0

你需要'#include 'strlen() – 2011-12-18 18:04:46

+0

@ Catcall:好,趕快,謝謝! – ruakh 2011-12-18 18:35:16

4

最快辦法做到這一點是可能

  • 創建該表沒有約束,
  • 使用外部程序來生成隨機數據,
  • 使用COPY將其加載到表
  • 然後添加約束。
相關問題