@@ -9,6 +9,7 @@ local cjson = require("cjson")
9
9
local http = require (" socket.http" )
10
10
local ltn12 = require (" ltn12" )
11
11
local pgmoon = require (" pgmoon" )
12
+ local pgvector = require (" ./src/pgvector" )
12
13
13
14
local pg = pgmoon .new ({
14
15
database = " pgvector_example" ,
@@ -20,14 +21,6 @@ assert(pg:query("CREATE EXTENSION IF NOT EXISTS vector"))
20
21
assert (pg :query (" DROP TABLE IF EXISTS documents" ))
21
22
assert (pg :query (" CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding sparsevec(30522))" ))
22
23
23
- function sparsevec (elements , dim )
24
- local e = {}
25
- for k , v in pairs (elements ) do
26
- table.insert (e , k .. " :" .. v )
27
- end
28
- return " {" .. table.concat (e , " ," ) .. " }/" .. dim
29
- end
30
-
31
24
function embed (inputs )
32
25
local url = " http://localhost:3000/embed_sparse"
33
26
local data = {
@@ -67,12 +60,12 @@ local documents = {
67
60
local embeddings = embed (documents )
68
61
for i , content in ipairs (documents ) do
69
62
local embedding = embeddings [i ]
70
- assert (pg :query (" INSERT INTO documents (content, embedding) VALUES ($1, $2::text::sparsevec )" , content , sparsevec (embedding , 30522 )))
63
+ assert (pg :query (" INSERT INTO documents (content, embedding) VALUES ($1, $2)" , content , pgvector . sparsevec (embedding , 30522 )))
71
64
end
72
65
73
66
local query = " forest"
74
67
local embedding = embed ({query })[1 ]
75
- local res = assert (pg :query (" SELECT content FROM documents ORDER BY embedding <#> $1::text::sparsevec LIMIT 5" , sparsevec (embedding , 30522 )))
68
+ local res = assert (pg :query (" SELECT content FROM documents ORDER BY embedding <#> $1 LIMIT 5" , pgvector . sparsevec (embedding , 30522 )))
76
69
for i , row in ipairs (res ) do
77
70
print (row [" content" ])
78
71
end
0 commit comments