資料庫新秀 postgresql vs mongo 效能PK
前幾天看了一篇文章<High Performance JSON PostgreSQL vs. MongoDB> 釋出在Percona Live Europe 2017
作者是<Dominic Dwyer Wei Shan Ang>,作者的觀點是PostgreSQL更好,恰巧沒有玩過postgresql,僅僅聽說過。
碼農的第一特徵就是相信實驗,故postgresql走起
上一篇文章<mongodb索引--1億條記錄的查詢從55.7秒到毫秒級別> 我們做了一個mongo的實驗
>>插入1億條記錄,約耗時1個小時
>>無索引查詢一條記錄耗時為55.7秒
>>有索引查詢一條記錄耗時小於1秒
1.去官網下載psotgresql :https://www.postgresql.org/
下載最新版本11.1 windows安裝,step by step
2.客戶端,我選了pgadmin:https://www.pgadmin.org/
下載最新版本v3.6 windows安裝,step by step
3.建立新的資料庫www
4.建立新表
/* String sql = "CREATE TABLE PERSON " + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql);*/
5.插入1億條記錄
java client 依賴包
<dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <version>42.2.5</version> </dependency>
java程式
public void postgresqlOneByOneInsert() {
try {
long start=System.currentTimeMillis();
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/www", "postgres", "root");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO PERSON(ID,NAME,AGE,ADDRESS,SALARY) values(?,?,?,?,?);"); for(int i=0;i<100000000;i++) { stmt.setInt(1, i+1); stmt.setString(2, "mkyong"+i); stmt.setInt(3, i%100); stmt.setString(4, "address"+i); stmt.setFloat(5, 25000.00f); stmt.executeUpdate(); } /* String sql = "CREATE TABLE PERSON " + "(ID INT PRIMARY KEY NOT NULL," + " NAME TEXT NOT NULL, " + " AGE INT NOT NULL, " + " ADDRESS CHAR(50), " + " SALARY REAL)"; stmt.executeUpdate(sql);*/ /* ResultSet rs = stmt.executeQuery( "SELECT * FROM STUDENT;" ); while ( rs.next() ) { int id = rs.getInt("sid"); String name = rs.getString("name"); System.out.println( "ID = " + id ); System.out.println( "NAME = " + name );; System.out.println(); } rs.close();*/ stmt.close(); connection.close(); System.out.println("耗時:"+(System.currentTimeMillis()-start)+" 毫秒"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
然後是漫長的時間等待插入完成。
>>插入效能:1億條記錄匯入時間耗時:36599195 毫秒~10個小時
>>無索引時讀取效能:SELECT * FROM PERSON where name='mkyong90000000'; 9 secs 574 msec
>>有索引時讀取效能:create index name_ind on PERSON(NAME); //建立索引耗時5 min 9 secs. SELECT * FROM PERSON where name='mkyong90000000'; //61ms
小結:
-
插入效能:mongo的效率為postgresql的10倍
-
讀取效能:無索引時,postgresql是mongo的6倍左右
- 建立索引:postgrep要快,有索引查詢不能確定查詢時間差異