Skip to content

Commit

Permalink
Improved example
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane committed Oct 31, 2023
1 parent 9e61a9d commit e742e7e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,19 @@ db.exec(sql"CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))")
Insert vectors

```nim
db.exec(sql"INSERT INTO items (embedding) VALUES (?), (?), (?)", "[1,1,1]", "[2,2,2]", "[1,1,2]")
import std/json
let embedding1 = %* @[1, 1, 1];
let embedding2 = %* @[1, 1, 2];
let embedding3 = %* @[2, 2, 2];
db.exec(sql"INSERT INTO items (embedding) VALUES (?), (?), (?)", embedding1, embedding2, embedding3)
```

Get the nearest neighbors

```nim
let rows = db.getAllRows(sql"SELECT * FROM items ORDER BY embedding <-> ? LIMIT 5", "[1,1,1]")
let embedding = %* @[1, 1, 1];
let rows = db.getAllRows(sql"SELECT * FROM items ORDER BY embedding <-> ? LIMIT 5", embedding)
for row in rows:
echo row
```
Expand Down
11 changes: 8 additions & 3 deletions example.nim
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import db_connector/db_postgres
import std/json

let db = db_postgres.open("localhost", "", "", "pgvector_nim_test")

Expand All @@ -7,11 +8,15 @@ db.exec(sql"DROP TABLE IF EXISTS items")

db.exec(sql"CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))")

db.exec(sql"INSERT INTO items (embedding) VALUES (?), (?), (?)", "[1,1,1]", "[2,2,2]", "[1,1,2]")
let embedding1 = %* @[1, 1, 1];
let embedding2 = %* @[1, 1, 2];
let embedding3 = %* @[2, 2, 2];
db.exec(sql"INSERT INTO items (embedding) VALUES (?), (?), (?)", embedding1, embedding2, embedding3)

let rows = db.getAllRows(sql"SELECT * FROM items ORDER BY embedding <-> ? LIMIT 5", "[1,1,1]")
let embedding = %* @[1, 1, 1];
let rows = db.getAllRows(sql"SELECT * FROM items ORDER BY embedding <-> ? LIMIT 5", embedding)
for row in rows:
echo row
echo row[0], ": ", parseJson(row[1])

db.exec(sql"CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)")

Expand Down

0 comments on commit e742e7e

Please sign in to comment.