|
| 1 | +package com.dolphindb.examples; |
| 2 | + |
| 3 | +import com.xxdb.*; |
| 4 | +import com.xxdb.data.*; |
| 5 | +import com.xxdb.data.Vector; |
| 6 | +import com.xxdb.route.AutoFitTableUpsert; |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +/** |
| 10 | + * ATFU(upsert) allows you to insert data idempotently, but the cost is quite high. |
| 11 | + * DO NOT use it frequently. |
| 12 | + */ |
| 13 | +public class AutoFitTableUpsertDemo { |
| 14 | + public static void main(String[] args) throws Exception { |
| 15 | + DBConnection conn = new DBConnection(false, false, false); |
| 16 | + conn.connect("localhost", 8848, "admin", "123456"); |
| 17 | + String dbName ="dfs://upsertTable"; |
| 18 | + String tableName = "pt"; |
| 19 | + String script = "dbName = \"dfs://upsertTable\"\n"+ |
| 20 | + "if(exists(dbName)){\n"+ |
| 21 | + "\tdropDatabase(dbName)\t\n"+ |
| 22 | + "}\n"+ |
| 23 | + "db = database(dbName, RANGE,1 10000,,'TSDB')\n"+ |
| 24 | + "t = table(1000:0, `id`value,[ INT, DOUBLE])\n"+ |
| 25 | + "pt = db.createPartitionedTable(t,`pt,`id,,`id)"; |
| 26 | + conn.run(script); |
| 27 | + |
| 28 | + BasicIntVector v1 = new BasicIntVector(3); |
| 29 | + v1.setInt(0, 1); |
| 30 | + v1.setInt(1, 100); |
| 31 | + v1.setInt(2, 1000); |
| 32 | + |
| 33 | + BasicDoubleVector v2 = new BasicDoubleVector(3); |
| 34 | + v2.setDouble(0, 100.0); |
| 35 | + v2.setDouble(1, 110.0); |
| 36 | + v2.setDouble(2, 108.0); |
| 37 | + |
| 38 | + List<String> colNames = new ArrayList<>(); |
| 39 | + colNames.add("id"); |
| 40 | + colNames.add("value"); |
| 41 | + List<Vector> cols = new ArrayList<>(); |
| 42 | + cols.add(v1); |
| 43 | + cols.add(v2); |
| 44 | + BasicTable bt = new BasicTable(colNames, cols); |
| 45 | + String[] keyColName = new String[]{"id"}; |
| 46 | + AutoFitTableUpsert aftu = new AutoFitTableUpsert(dbName, tableName, conn, false, keyColName, null); |
| 47 | + aftu.upsert(bt); |
| 48 | + BasicTable res = (BasicTable) conn.run("select * from pt;"); |
| 49 | + System.out.println(res.getString()); |
| 50 | + |
| 51 | + //第2次插入pt,会根据id去重,存在则更新,否则插入 |
| 52 | + BasicIntVector v3 = new BasicIntVector(3); |
| 53 | + v3.setInt(0, 1); |
| 54 | + v3.setInt(1, 1001); |
| 55 | + v3.setInt(2, 1002); |
| 56 | + |
| 57 | + BasicDoubleVector v4 = new BasicDoubleVector(3); |
| 58 | + v4.setDouble(0, 120.0); |
| 59 | + v4.setDouble(1, 130.0); |
| 60 | + v4.setDouble(2, 140.0); |
| 61 | + |
| 62 | + cols.set(0, v3); |
| 63 | + cols.set(1, v4); |
| 64 | + bt.setColumns(cols); |
| 65 | + |
| 66 | + aftu.upsert(bt); |
| 67 | + BasicTable res2 = (BasicTable) conn.run("select * from pt;"); |
| 68 | + System.out.println(res2.getString()); |
| 69 | + } |
| 70 | +} |
| 71 | + |
0 commit comments