|
| 1 | +# pgvector-d |
| 2 | + |
| 3 | +[pgvector](https://github.com/pgvector/pgvector) examples for D |
| 4 | + |
| 5 | +Supports [dpq2](https://github.com/denizzzka/dpq2) |
| 6 | + |
| 7 | +[](https://github.com/pgvector/pgvector-d/actions) |
| 8 | + |
| 9 | +## Getting Started |
| 10 | + |
| 11 | +Follow the instructions for your database library: |
| 12 | + |
| 13 | +- [dpq2](#dpq2) |
| 14 | + |
| 15 | +## dpq2 |
| 16 | + |
| 17 | +Enable the extension |
| 18 | + |
| 19 | +```d |
| 20 | +conn.exec("CREATE EXTENSION IF NOT EXISTS vector"); |
| 21 | +``` |
| 22 | + |
| 23 | +Create a table |
| 24 | + |
| 25 | +```d |
| 26 | +conn.exec("CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))"); |
| 27 | +``` |
| 28 | + |
| 29 | +Insert vectors |
| 30 | + |
| 31 | +```d |
| 32 | +QueryParams p; |
| 33 | +p.sqlCommand = "INSERT INTO items (embedding) VALUES ($1::vector), ($2::vector)"; |
| 34 | +p.argsVariadic("[1,2,3]", "[4,5,6]"); |
| 35 | +conn.execParams(p); |
| 36 | +``` |
| 37 | + |
| 38 | +Get the nearest neighbors |
| 39 | + |
| 40 | +```d |
| 41 | +QueryParams p; |
| 42 | +p.sqlCommand = "SELECT * FROM items ORDER BY embedding <-> $1::vector LIMIT 5"; |
| 43 | +p.argsVariadic("[3,1,2]"); |
| 44 | +p.resultFormat = ValueFormat.TEXT; |
| 45 | +auto r = conn.execParams(p); |
| 46 | +foreach (row; rangify(r)) { |
| 47 | + writeln(row); |
| 48 | +} |
| 49 | +``` |
| 50 | + |
| 51 | +Add an approximate index |
| 52 | + |
| 53 | +```d |
| 54 | +conn.exec("CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)"); |
| 55 | +// or |
| 56 | +conn.exec("CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)"); |
| 57 | +``` |
| 58 | + |
| 59 | +Use `vector_ip_ops` for inner product and `vector_cosine_ops` for cosine distance |
| 60 | + |
| 61 | +See a [full example](source/app.d) |
| 62 | + |
| 63 | +## Contributing |
| 64 | + |
| 65 | +Everyone is encouraged to help improve this project. Here are a few ways you can help: |
| 66 | + |
| 67 | +- [Report bugs](https://github.com/pgvector/pgvector-d/issues) |
| 68 | +- Fix bugs and [submit pull requests](https://github.com/pgvector/pgvector-d/pulls) |
| 69 | +- Write, clarify, or fix documentation |
| 70 | +- Suggest or add new features |
| 71 | + |
| 72 | +To get started with development: |
| 73 | + |
| 74 | +```sh |
| 75 | +git clone https://github.com/pgvector/pgvector-d.git |
| 76 | +cd pgvector-d |
| 77 | +createdb pgvector_d_test |
| 78 | +dub run |
| 79 | +``` |
| 80 | + |
| 81 | +Specify the path to libpq if needed: |
| 82 | + |
| 83 | +```sh |
| 84 | +DFLAGS="-L-L/opt/homebrew/opt/libpq/lib" dub run |
| 85 | +``` |
0 commit comments