Skip to content

Commit 6064f02

Browse files
committed
Updated loading example to use binary copy [skip ci]
1 parent d0666b5 commit 6064f02

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

examples/loading/src/main/java/com/example/Example.java

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import org.postgresql.copy.CopyIn;
1010
import org.postgresql.copy.CopyManager;
1111
import org.postgresql.core.BaseConnection;
12+
import org.postgresql.util.ByteConverter;
1213

1314
public class Example {
1415
public static void main(String[] args) throws SQLException {
@@ -38,17 +39,34 @@ public static void main(String[] args) throws SQLException {
3839
System.out.println("Loading 1000000 rows");
3940

4041
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+
4353
for (int i = 0; i < rows; i++) {
4454
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());
4761

4862
if (i % 10000 == 0) {
4963
System.out.print(".");
5064
}
5165
}
66+
67+
// write trailer
68+
ByteConverter.int2(buffer, 0, -1);
69+
copyIn.writeToCopy(buffer, 0, 2);
5270
copyIn.endCopy();
5371

5472
System.out.println("\nSuccess!");

0 commit comments

Comments
 (0)