pgvector support for Node.js
Supports Sequelize, node-postgres, pg-promise, and Prisma
Run:
npm install pgvectorAnd follow the instructions for your database library:
Register the type
const { Sequelize } = require('sequelize');
const pgvector = require('pgvector/sequelize');
pgvector.registerType(Sequelize);Add a vector field
Item.init({
embedding: {
type: DataTypes.VECTOR(3)
}
}, ...);Insert a vector
await Item.create({embedding: [1, 2, 3]});Get the nearest neighbors to a vector
const items = await Item.findAll({
order: [sequelize.literal(`embedding <-> '[1, 2, 3]'`)],
limit: 5
});Register the type
const pgvector = require('pgvector/pg');
await pgvector.registerType(client);Insert a vector
const embedding = [1, 2, 3];
await client.query('INSERT INTO items (embedding) VALUES ($1)', [pgvector.toSql(embedding)]);Get the nearest neighbors to a vector
const result = await client.query('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [pgvector.toSql(embedding)]);Register the type
const pgvector = require('pgvector/pg');
const initOptions = {
async connect(e) {
await pgvector.registerType(e.client);
}
};
const pgp = require('pg-promise')(initOptions);Insert a vector
const embedding = [1, 2, 3];
await db.none('INSERT INTO items (embedding) VALUES ($1)', [pgvector.toSql(embedding)]);Get the nearest neighbors to a vector
const result = await db.any('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [pgvector.toSql(embedding)]);Import the library
const pgvector = require('pgvector/utils')Add the extension to the schema
generator client {
provider = "prisma-client-js"
previewFeatures = ["postgresqlExtensions"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
extensions = [vector]
}Add a vector column to the schema
model Item {
id Int @id @default(autoincrement())
embedding Unsupported("vector(3)")?
}Insert a vector
const embedding = pgvector.toSql([1, 1, 1])
await prisma.$executeRaw`INSERT INTO items (embedding) VALUES (${embedding}::vector)`Get the nearest neighbors to a vector
const embedding = pgvector.toSql([1, 1, 1])
const items = await prisma.$queryRaw`SELECT id, embedding::text FROM items ORDER BY embedding <-> ${embedding}::vector LIMIT 5`View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
git clone https://github.com/pgvector/pgvector-node.git
cd pgvector-node
npm install
npm run build:cjs
createdb pgvector_node_test
npx prisma migrate dev
npm test