前言
本文繼續學習PostgreSQL, 看到PostgreSQL有個Array欄位,感覺可以用來存盤某種表,比如股票每天的價格, 我們稱為market_price表,先來看下最開始market_price 表的定義
create table market_price(
id char(10),
trade_date date,
open float ,
high float,
low float,
close float,
primary key (id,trade_date)
);
表說明
id 每支股票有個對應的編號,
trade_date是交易日期,
open high low close分別代表開盤價,最高價,最低價,收盤價,
這樣定義表結構,我們要查詢某天的價格非常方便,給定id和日期就能查出來,但是有個問題就是存到postgreSQL后, 記錄會非常多,假設全球有10萬只股票,我們存盤從1990到今天的資料,那么中間的日期數量就是每支股票有大概12000條記錄,總記錄數就是有12億條記錄,對于關系型資料庫資料上億后,查詢性能會下降比較明顯, 有什么辦法可以把記錄數減少一些呢? 我們可以嘗試一下Array來存盤下, 看這樣的表結構
create table market_price_month_array(
id char(10),
year smallint,
month smallint,
open float array[31],
high float array[31],
low float array[31],
close float array[31]
primary key (id,year,month)
);
我們這里使用了Array,把每個月的資料存成1行,每個月都按31天算,open[1]就表示第一天, open[2] 就表示第2天, 這樣資料行數能減少30倍,12億行變成4千萬行,查詢性能會好很多,
下面是存入和更新的例子
postgres=# insert into market_price_month_array values('0P00000001',2023,2,'{2.11,2.12,2.13,2.14,2.15,2.16,2.17,2.18,2.19}','{4.11,4.12,4.13,4.14,4.15,4.16,4.17,4.18,4.19}','{1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,1.19}','{3.11,3.12,3.13,3.14,3.15,3.16,3.17,3.18,3.19}');
INSERT 0 1
postgres=# select * from market_price_month_array;
0P00000001 | 2023 | 2 | {2.11,2.12,2.13,2.14,2.15,2.16,2.17,2.18,2.19} | {4.11,4.12,4.13,4.14,4.15,4.16,4.17,4.18,4.19} | {1.11,1.12,1.13,1.14,1.15,1.16,1.17,1.18,1.19} | {3.11,3.12,3.
13,3.14,3.15,3.16,3.17,3.18,3.19}
(1 row)
postgres=# update market_price_month_array set open[19] = 2.19, high[19] = 4.19, low[19]= 1.19, close[19]=3.19 where id = '0P00000001' and year = 2023 and month = 2;
UPDATE 1
postgres=# select * from market_price_month_array;
0P00000001 | 2023 | 2 | {2.11,2.12,2.13,2.14,2.15,2.16,2.17,NULL,2.19,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,2.19} | {4.11,4.12,4.13,4.14,4.15,4.16,4.17,NULL,4.19,NULL,NULL,NULL,
NULL,NULL,NULL,NULL,NULL,NULL,4.19} | {1.11,1.12,1.13,1.14,1.15,1.16,1.17,NULL,1.19,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1.19} | {3.11,3.12,3.13,3.14,3.15,3.16,3.17,NULL,3.19,NULL,N
ULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,3.19}
插入的時候,值用“'{2.11,2.12,2.13,2.14,2.15,2.16,2.17,2.18,2.19}'”, 沒有的日期就自動設定為NULL了,
想更新哪一天的,就直接用close[19]=3.19, 使用非常方便,
那么我們想要用Java來進行插入資料應該怎么做呢? 是不是和其他非陣列的型別一樣的用法吶?當然是有些不一樣的,下面部分就是如何使用Spring來保存Array型別,
JPA 方式保存
JPA方式是我們存入資料庫的時候最方便的方式,定義個entity, 然后定義個介面就能干活了,
但是這里直接在Entity里面這樣定義Double[] open是不行的,需要加一個型別轉化,我參考了這篇文章https://www.baeldung.com/java-hibernate-map-postgresql-array
這里直接給代碼
package ken.postgresql.poc;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "market_price_month_array")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class MarketPriceMonth {
@EmbeddedId
private MarketPriceMonthKey id;
@Column(columnDefinition = "float[]")
@Type(type = "ken.postgresql.poc.arraymapping.CustomDoubleArrayType")
private Double[] open;
@Column(columnDefinition = "float[]")
@Type(type = "ken.postgresql.poc.arraymapping.CustomDoubleArrayType")
private Double[] high;
@Column(columnDefinition = "float[]")
@Type(type = "ken.postgresql.poc.arraymapping.CustomDoubleArrayType")
private Double[] low;
@Column(columnDefinition = "float[]")
@Type(type = "ken.postgresql.poc.arraymapping.CustomDoubleArrayType")
private Double[] close;
}
自定義CustomDoubleArrayType代碼
package ken.postgresql.poc.arraymapping;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;
import java.io.Serializable;
import java.sql.Array;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
public class CustomDoubleArrayType implements UserType {
@Override
public int[] sqlTypes() {
return new int[]{Types.ARRAY};
}
@Override
public Class returnedClass() {
return Double[].class;
}
@Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x instanceof Double[] && y instanceof Double[]) {
return Arrays.deepEquals((Double[])x, (Double[])y);
} else {
return false;
}
}
@Override
public int hashCode(Object x) throws HibernateException {
return Arrays.hashCode((Double[])x);
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner)
throws HibernateException, SQLException {
Array array = rs.getArray(names[0]);
return array != null ? array.getArray() : null;
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session)
throws HibernateException, SQLException {
if (value != null && st != null) {
Array array = session.connection().createArrayOf("float", (Double[])value);
st.setArray(index, array);
} else {
st.setNull(index, sqlTypes()[0]);
}
}
@Override
public Object deepCopy(Object value) throws HibernateException {
Double[] a = (Double[]) value;
return Arrays.copyOf(a, a.length);
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
}
定義介面后就可以直接使用了
public interface MarketPriceMonthRepository extends JpaRepository<MarketPriceMonth, MarketPriceMonthKey> {
}
jdbcTemplate Batch保存
上面的方法一條條保存沒有問題,但是當資料量大的時候,比如我們批量把資料匯入的時候,一條條保存就很不給力了,我們需要用batch方法, 這里有一篇batch和不用batch對比性能的文章https://www.baeldung.com/spring-jdbc-batch-inserts
使用jdbcTemplate.batchUpdate 方法來批量保存
batchUpdate 有四個引數
batchUpdate(
String sql,
Collection
int batchSize,
ParameterizedPreparedStatementSetter
batchArgs 是我們需要保存的資料
batchSize 是我們一次保存多少條,可以自動幫我們把batchArgs里面的資料分次保存
pss 是一個FunctionalInterface,可以接受Lambda運算式,
(PreparedStatement ps, MarketPriceMonth marketPriceMonth) -> {
#這里給ps設定值
};
PreparedStatement 有個ps.setArray(int parameterIndex, Array x)方法,
我們需要做得就是創建一個Array,
有一個方法創建方法是這樣的, 呼叫connection的方法來create array
private java.sql.Array createSqlArray(Double[] list){
java.sql.Array intArray = null;
try {
intArray = jdbcTemplate.getDataSource().getConnection().createArrayOf("float", list);
} catch (SQLException ignore) {
log.error("meet error",ignore);
}
return intArray;
}
但是我使用的時候,這個方法很慢,沒有成功,感覺不行,
后來換成了自定義一個繼承java.sql.Array的類來轉換陣列,
package ken.postgresql.poc.repostory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
import java.util.Map;
public class PostgreSQLDoubleArray implements java.sql.Array {
private final Double[] doubleArray;
private final String stringValue;
public PostgreSQLDoubleArray(Double[] intArray) {
this.doubleArray = intArray;
this.stringValue = https://www.cnblogs.com/dk168/archive/2023/02/24/intArrayToPostgreSQLInt4ArrayString(intArray);
}
public String toString() {
return stringValue;
}
/**
* This static method can be used to convert an integer array to string representation of PostgreSQL integer array.
*
* @param a source integer array
* @return string representation of a given integer array
*/
public static String intArrayToPostgreSQLInt4ArrayString(Double[] a) {
if (a == null) {
return"NULL";
}
final int al = a.length;
if (al == 0) {
return "{}";
}
StringBuilder sb = new StringBuilder(); // as we usually operate with 6 digit numbers + 1 symbol for a delimiting comma
sb.append('{');
for (int i = 0; i < al; i++) {
if (i > 0) sb.append(',');
sb.append(a[i]);
}
sb.append('}');
return sb.toString();
}
@Override
public Object getArray() throws SQLException {
return doubleArray == null ? null : Arrays.copyOf(doubleArray, doubleArray.length);
}
@Override
public Object getArray(Map<String, Class<?>> map) throws SQLException {
return getArray();
}
public Object getArray(long index, int count) throws SQLException {
return doubleArray == null ? null : Arrays.copyOfRange(doubleArray, (int) index, (int) index + count);
}
public Object getArray(long index, int count, Map<String, Class<?>> map) throws SQLException {
return getArray(index, count);
}
public int getBaseType() throws SQLException {
return Types.DOUBLE;
}
public String getBaseTypeName() throws SQLException {
return "float";
}
public ResultSet getResultSet() throws SQLException {
throw new UnsupportedOperationException();
}
public ResultSet getResultSet(Map<String, Class<?>> map) throws SQLException {
throw new UnsupportedOperationException();
}
public ResultSet getResultSet(long index, int count) throws SQLException {
throw new UnsupportedOperationException();
}
public ResultSet getResultSet(long index, int count, Map<String, Class<?>> map) throws SQLException {
throw new UnsupportedOperationException();
}
public void free() throws SQLException {
}
}
就是把陣列拼成string后傳進去,
這樣呼叫
public void saveAll(List<MarketPriceMonth> marketPriceMonthList)
{
this.jdbcTemplate.batchUpdate("INSERT INTO market_price_month_array (id, year, month, open, high, low, close) VALUES (?,?,?,?,?,?,?)",
marketPriceMonthList,
100,
(PreparedStatement ps, MarketPriceMonth marketPriceMonth) -> {
MarketPriceMonthKey key = marketPriceMonth.getId();
ps.setString(1, key.getId());
ps.setInt(2, key.getYear());
ps.setInt(3, key.getMonth());
ps.setArray(4, new PostgreSQLDoubleArray(marketPriceMonth.getOpen()));
ps.setArray(5, new PostgreSQLDoubleArray(marketPriceMonth.getHigh()));
ps.setArray(6, new PostgreSQLDoubleArray(marketPriceMonth.getLow()));
ps.setArray(7, new PostgreSQLDoubleArray(marketPriceMonth.getClose()));
});
}
我也嘗試過直接用String, 然后自己拼接這個string,沒有成功,報型別轉換錯誤!
ps.setString(1, createArrayString(marketPriceMonth.getOpen()));
private String createArrayString(Double[] list)
{
StringBuilder stringBuilder = new StringBuilder();
for (Double d:list
) {
if (stringBuilder.length() != 0)
{
stringBuilder.append(",");
}
stringBuilder.append(d!=null?d.toString():"null");
}
return stringBuilder.toString();
}
使用batch后,本機測驗,性能提升非常明顯,
總結
這篇文章是我這周解決問題的一個記錄,看起來非常簡單,但是也花了我一些時間,找到了一個可以快速保存Array型別資料到postgresql的方法,遇到問題解決問題,然后解決了是非常好的一種提升技能的方式, 這里不知道有沒有更簡單的方法,要是有就好了,省得寫這么多自定義的型別,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544939.html
標籤:其他
上一篇:位操作運算
