@@ -9,6 +9,7 @@ local cjson = require("cjson")
99local http = require (" socket.http" )
1010local ltn12 = require (" ltn12" )
1111local pgmoon = require (" pgmoon" )
12+ local pgvector = require (" ./src/pgvector" )
1213
1314local pg = pgmoon .new ({
1415 database = " pgvector_example" ,
@@ -20,14 +21,6 @@ assert(pg:query("CREATE EXTENSION IF NOT EXISTS vector"))
2021assert (pg :query (" DROP TABLE IF EXISTS documents" ))
2122assert (pg :query (" CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding sparsevec(30522))" ))
2223
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-
3124function embed (inputs )
3225 local url = " http://localhost:3000/embed_sparse"
3326 local data = {
@@ -67,12 +60,12 @@ local documents = {
6760local embeddings = embed (documents )
6861for i , content in ipairs (documents ) do
6962 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 )))
7164end
7265
7366local query = " forest"
7467local 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 )))
7669for i , row in ipairs (res ) do
7770 print (row [" content" ])
7871end
0 commit comments