前几天看了一篇文章<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要快,有索引查询不能确定查询时间差异