|
9 | 9 | import org.postgresql.copy.CopyIn; |
10 | 10 | import org.postgresql.copy.CopyManager; |
11 | 11 | import org.postgresql.core.BaseConnection; |
| 12 | +import org.postgresql.util.ByteConverter; |
12 | 13 |
|
13 | 14 | public class Example { |
14 | 15 | public static void main(String[] args) throws SQLException { |
@@ -38,17 +39,34 @@ public static void main(String[] args) throws SQLException { |
38 | 39 | System.out.println("Loading 1000000 rows"); |
39 | 40 |
|
40 | 41 | CopyManager copyManager = new CopyManager((BaseConnection) conn); |
41 | | - // TODO use binary format |
42 | | - CopyIn copyIn = copyManager.copyIn("COPY items (embedding) FROM STDIN"); |
| 42 | + CopyIn copyIn = copyManager.copyIn("COPY items (embedding) FROM STDIN WITH (FORMAT BINARY)"); |
| 43 | + |
| 44 | + // write header |
| 45 | + // https://www.postgresql.org/docs/current/sql-copy.html |
| 46 | + byte[] buffer = new byte[32768]; |
| 47 | + byte[] signature = new byte[] {80, 71, 67, 79, 80, 89, 10, (byte)255, 13, 10, 0}; |
| 48 | + System.arraycopy(signature, 0, buffer, 0, signature.length); |
| 49 | + ByteConverter.int4(buffer, 11, 0); |
| 50 | + ByteConverter.int4(buffer, 15, 0); |
| 51 | + copyIn.writeToCopy(buffer, 0, 19); |
| 52 | + |
43 | 53 | for (int i = 0; i < rows; i++) { |
44 | 54 | PGvector embedding = new PGvector(embeddings.get(i)); |
45 | | - byte[] bytes = (embedding.getValue() + "\n").getBytes(); |
46 | | - copyIn.writeToCopy(bytes, 0, bytes.length); |
| 55 | + |
| 56 | + // write row |
| 57 | + ByteConverter.int2(buffer, 0, 1); |
| 58 | + ByteConverter.int4(buffer, 2, embedding.lengthInBytes()); |
| 59 | + embedding.toBytes(buffer, 6); |
| 60 | + copyIn.writeToCopy(buffer, 0, 6 + embedding.lengthInBytes()); |
47 | 61 |
|
48 | 62 | if (i % 10000 == 0) { |
49 | 63 | System.out.print("."); |
50 | 64 | } |
51 | 65 | } |
| 66 | + |
| 67 | + // write trailer |
| 68 | + ByteConverter.int2(buffer, 0, -1); |
| 69 | + copyIn.writeToCopy(buffer, 0, 2); |
52 | 70 | copyIn.endCopy(); |
53 | 71 |
|
54 | 72 | System.out.println("\nSuccess!"); |
|
0 commit comments