### Run Example Project Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Install dependencies, create a database, and run an example project located in the 'examples/loading' directory. ```sh cd examples/loading npm install createdb pgvector_example node example.js ``` -------------------------------- ### Install Dependencies and Setup Database for Development Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Install project dependencies using npm, create a test database, generate Prisma schema, and apply migrations. ```sh npm install createdb pgvector_node_test npx prisma generate npx prisma migrate dev ``` -------------------------------- ### Install pgvector Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Install the pgvector package using npm. This is the initial step before integrating with specific database libraries. ```sh npm install pgvector ``` -------------------------------- ### Prisma: Get Nearest Neighbors Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for nearest neighbors using Prisma. The `<->` operator calculates the Euclidean distance, and results are ordered by this distance. ```javascript const embedding = pgvector.toSql([1, 2, 3]) const items = await prisma.$queryRaw`SELECT id, embedding::text FROM items ORDER BY embedding <-> ${embedding}::vector LIMIT 5` ``` -------------------------------- ### MikroORM: Get Nearest Neighbors (L2 Distance) Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for nearest neighbors using MikroORM's QueryBuilder and the `l2Distance` function. This calculates the Euclidean distance. ```javascript import { l2Distance } from 'pgvector/mikro-orm'; const items = await em.createQueryBuilder(Item) .orderBy({[l2Distance('embedding', [1, 2, 3])]: 'ASC'}) .limit(5) .getResult(); ``` -------------------------------- ### Find Nearest Neighbors with Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve the nearest neighbors to a given vector using Knex.js. This example uses the `l2Distance` helper function provided by the pgvector adapter and limits the results. ```javascript const items = await knex('items') .orderBy(knex.l2Distance('embedding', [1, 2, 3])) .limit(5); ``` -------------------------------- ### Get nearest neighbors with L2 distance using Objection.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for the 5 nearest neighbors to a given vector using the L2 distance. Requires importing l2Distance from pgvector/objection. ```javascript import { l2Distance } from 'pgvector/objection'; const items = await Item.query() .orderBy(l2Distance('embedding', [1, 2, 3])) .limit(5); ``` -------------------------------- ### Get nearest neighbors with pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve the 5 nearest neighbors to a given vector using the '<->' operator for distance calculation. Uses pgvector.toSql for formatting. ```javascript const result = await db.any('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [pgvector.toSql([1, 2, 3])]); ``` -------------------------------- ### Postgres.js: Get Nearest Neighbors Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve nearest neighbors to a given vector using Postgres.js. The `<->` operator is used for Euclidean distance. ```javascript const embedding = pgvector.toSql([1, 2, 3]); const items = await sql`SELECT * FROM items ORDER BY embedding <-> ${ embedding } LIMIT 5`; ``` -------------------------------- ### Find Nearest Neighbors with node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for the nearest neighbors to a given vector using node-postgres. This example uses the L2 distance operator '<->' and limits the results to 5. ```javascript const result = await client.query('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [pgvector.toSql([1, 2, 3])]); ``` -------------------------------- ### Get Sparse Vector Dimensions Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve the total number of dimensions defined for the `SparseVector`. ```javascript const dim = vec.dimensions; ``` -------------------------------- ### Get Sparse Vector Non-Zero Values Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve an array of the values corresponding to the non-zero elements in the `SparseVector`. ```javascript const values = vec.values; ``` -------------------------------- ### Get nearest neighbors with L2 distance using Sequelize Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for the 5 nearest neighbors using L2 distance. Requires importing l2Distance from pgvector/sequelize and passing the sequelize instance. ```javascript import { l2Distance } from 'pgvector/sequelize'; const items = await Item.findAll({ order: l2Distance('embedding', [1, 1, 1], sequelize), limit: 5 }); ``` -------------------------------- ### Get nearest neighbors with L2 distance using Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve the 5 nearest neighbors to a given vector using L2 distance. Requires importing l2Distance from pgvector/kysely. ```javascript import { l2Distance } from 'pgvector/kysely'; const items = await db.selectFrom('items') .selectAll() .orderBy(l2Distance('embedding', [1, 2, 3])) .limit(5) .execute(); ``` -------------------------------- ### Get Sparse Vector Non-Zero Indices Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Access an array containing the indices of all non-zero elements within the `SparseVector`. ```javascript const indices = vec.indices; ``` -------------------------------- ### Create Table with Vector Column using node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create a table with a vector column using node-postgres. Specify the dimension of the vector, for example, 3 dimensions in this case. ```javascript await client.query('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))'); ``` -------------------------------- ### TypeORM: Get Nearest Neighbors Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for nearest neighbors using TypeORM's QueryBuilder. Use the `<->` operator and set parameters for the embedding vector. ```javascript import pgvector from 'pgvector'; const items = await itemRepository .createQueryBuilder('item') .orderBy('embedding <-> :embedding') .setParameters({embedding: pgvector.toSql([1, 2, 3])}) .limit(5) .getMany(); ``` -------------------------------- ### Slonik: Get Nearest Neighbors Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Query for nearest neighbors with Slonik. The `<->` operator calculates Euclidean distance. Ensure the embedding is cast to `vector` if necessary. ```javascript const embedding = pgvector.toSql([1, 2, 3]); const items = await pool.query(sql.unsafe`SELECT * FROM items ORDER BY embedding <-> ${embedding} LIMIT 5`); ``` -------------------------------- ### Get items within a certain distance using Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Select items where the L2 distance between the 'embedding' column and a target vector is less than 5. Uses l2Distance from pgvector/kysely. ```javascript const items = await db.selectFrom('items') .selectAll() .where(l2Distance('embedding', [1, 2, 3]), '<', 5) .execute(); ``` -------------------------------- ### Run Tests Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Execute the test suite for pgvector-node using npm. ```sh npm test ``` -------------------------------- ### MikroORM: Enable Extension Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension using MikroORM's `em.execute` method. ```javascript await em.execute('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Import pgvector Library for deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Import the pgvector library for use with deno-postgres. This is the initial step to interact with pgvector functionalities. ```javascript import pgvector from 'npm:pgvector'; ``` -------------------------------- ### Slonik: Add Approximate Index (IVFFlat) Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an IVFFlat index with Slonik. Configure the `lists` parameter for performance tuning. ```javascript await pool.query(sql.unsafe`CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)`); ``` -------------------------------- ### Enable vector extension with pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the 'vector' extension in the database using pg-promise's `db.none` method. ```javascript await db.none('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Slonik: Enable Extension Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension using Slonik. Use `sql.unsafe` for raw SQL execution. ```javascript await pool.query(sql.unsafe`CREATE EXTENSION IF NOT EXISTS vector`); ``` -------------------------------- ### Enable vector extension with Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the 'vector' extension in the database using Kysely's SQL execution capabilities. ```javascript await sql`CREATE EXTENSION IF NOT EXISTS vector`.execute(db); ``` -------------------------------- ### Enable pgvector Extension with deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension in your PostgreSQL database using deno-postgres. This command should be run before creating tables with vector types. ```javascript await client.queryArray`CREATE EXTENSION IF NOT EXISTS vector`; ``` -------------------------------- ### Add Approximate L2 Index with IVFflat using node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an approximate nearest neighbor (ANN) index using the Inverted File (IVF) with a flat quantizer for L2 distance with node-postgres. Configure the number of lists for the index. ```javascript await client.query('CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)'); ``` -------------------------------- ### Postgres.js: Enable Extension Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension in your PostgreSQL database using Postgres.js. This should be done before creating vector columns. ```javascript await sql`CREATE EXTENSION IF NOT EXISTS vector`; ``` -------------------------------- ### Prisma: Enable pgvector Extension Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Configure your Prisma schema to use the PostgreSQL vector extension. Ensure `postgresqlExtensions` is enabled in your generator. ```prisma generator client { provider = "prisma-client" previewFeatures = ["postgresqlExtensions"] } datasource db { provider = "postgresql" extensions = [vector] } ``` -------------------------------- ### Postgres.js: Add Approximate Index (IVFFlat) Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an IVFFlat index for approximate nearest neighbor search. The `lists` parameter controls the number of lists (sub-quantizers). ```javascript await sql`CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)`; ``` -------------------------------- ### Insert Vectors with Bun SQL Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert multiple vectors into a table using Bun SQL. Utilize `pgvector.toSql()` for correct vector formatting and the `sql()` tag for efficient insertion. ```javascript const newItems = [ {embedding: pgvector.toSql([1, 2, 3])}, {embedding: pgvector.toSql([4, 5, 6])} ]; await sql`INSERT INTO items ${sql(newItems)}`; ``` -------------------------------- ### Create Table with Vector Column using deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table with a vector column using deno-postgres. Specify the vector dimensions as required. ```javascript await client.queryArray`CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))`; ``` -------------------------------- ### Postgres.js: Create Table Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create a table with a vector column using Postgres.js. Specify the dimension of the vector, e.g., `vector(3)`. ```javascript await sql`CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))`; ``` -------------------------------- ### Add Approximate Index with deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an approximate nearest neighbor (ANN) index for faster vector searches using deno-postgres. Supports HNSW and IVFFlat indexes. Use appropriate `vector_ops` for the desired distance metric. ```javascript await client.queryArray`CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)`; // or await client.queryArray`CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)`; ``` -------------------------------- ### Clone pgvector-node Repository Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Clone the pgvector-node repository from GitHub to set up the development environment. ```sh git clone https://github.com/pgvector/pgvector-node.git cd pgvector-node ``` -------------------------------- ### Postgres.js: Add Approximate Index (HNSW) Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an HNSW (Hierarchical Navigable Small World) index for efficient approximate nearest neighbor search on vector columns. Use `vector_l2_ops` for Euclidean distance. ```javascript await sql`CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)`; ``` -------------------------------- ### Import pgvector for Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Import the pgvector library for use with Kysely, including the toSql function. ```javascript import pgvector from 'pgvector/kysely'; ``` -------------------------------- ### Import pgvector Library Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Import the pgvector library for use in your Node.js project. ```javascript import pgvector from 'pgvector'; ``` -------------------------------- ### TypeORM: Enable Extension Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension using TypeORM. This requires direct SQL execution. ```javascript await AppDataSource.query('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Import pgvector for Objection.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Import the pgvector library specifically for use with Objection.js. ```javascript import pgvector from 'pgvector/objection'; ``` -------------------------------- ### Enable pgvector Extension with Drizzle ORM Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Use this SQL command to enable the pgvector extension if it's not already present. This is a prerequisite for using vector types in your database. ```javascript await client`CREATE EXTENSION IF NOT EXISTS vector`; ``` -------------------------------- ### Add Approximate Index with Bun SQL Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an approximate nearest neighbor (ANN) index for efficient vector searches with Bun SQL. Supports HNSW and IVFFlat indexes. Use the appropriate `vector_ops` for your chosen distance metric. ```javascript await sql`CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)`; // or await sql`CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)`; ``` -------------------------------- ### Slonik: Create Table Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table with a vector column using Slonik. Ensure the `vector` type and dimension are specified. ```javascript await pool.query(sql.unsafe`CREATE TABLE items (id serial PRIMARY KEY, embedding vector(3))`); ``` -------------------------------- ### Insert Vector with deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a vector into the database using deno-postgres. Use `pgvector.toSql()` to format the vector data correctly for SQL insertion. ```javascript const embedding = pgvector.toSql([1, 2, 3]); await client.queryArray`INSERT INTO items (embedding) VALUES (${embedding})`; ``` -------------------------------- ### TypeORM: Create Table Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create a table with a vector column using TypeORM. Specify the column type as 'vector' and its length. ```javascript await AppDataSource.query('CREATE TABLE item (id bigserial PRIMARY KEY, embedding vector(3))'); ``` -------------------------------- ### Enable vector extension with Sequelize Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the 'vector' extension in the database using Sequelize's query interface. ```javascript await sequelize.query('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Enable Vector Extension with Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension in your PostgreSQL database using Knex.js schema builder. This ensures the 'vector' type is available. ```javascript await knex.schema.createExtensionIfNotExists('vector'); ``` -------------------------------- ### Create items table with vector column using pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table named 'items' with an 'id' and a 'embedding' column of type vector(3) using a raw SQL query with pg-promise. ```javascript await db.none('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))'); ``` -------------------------------- ### Insert Vectors using Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert multiple records with vector embeddings into a table using Knex.js. The pgvector.toSql() function is used to format the vector data for SQL insertion. ```javascript const newItems = [ {embedding: pgvector.toSql([1, 2, 3])}, {embedding: pgvector.toSql([4, 5, 6])} ]; await knex('items').insert(newItems); ``` -------------------------------- ### Postgres.js: Insert Vectors Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert multiple vectors into a table using Postgres.js. The `sql()` function can handle array of objects for bulk inserts. ```javascript const newItems = [ {embedding: pgvector.toSql([1, 2, 3])}, {embedding: pgvector.toSql([4, 5, 6])} ]; await sql`INSERT INTO items ${ sql(newItems, 'embedding') }`; ``` -------------------------------- ### Query Nearest Neighbors with deno-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve nearest neighbors using a vector similarity search with deno-postgres. The `<->` operator is used for L2 distance. Ensure the vector is formatted with `pgvector.toSql()`. ```javascript const embedding = pgvector.toSql([1, 2, 3]); const { rows } = await client.queryArray`SELECT * FROM items ORDER BY embedding <-> ${embedding} LIMIT 5`; ``` -------------------------------- ### Create Table with Vector Column using Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table with a vector column using Knex.js schema builder. The 'vector' type is provided by the pgvector adapter. ```javascript await knex.schema.createTable('items', (table) => { table.increments('id'); table.vector('embedding', 3); }); ``` -------------------------------- ### Enable Vector Extension with node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Enable the pgvector extension in your PostgreSQL database using a node-postgres client. This is a prerequisite for using vector data types. ```javascript await client.query('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### MikroORM: Insert Vector Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a vector into an entity using MikroORM's `em.create` method. The vector is automatically handled by the `VectorType`. ```javascript em.create(Item, {embedding: [1, 2, 3]}); ``` -------------------------------- ### Add Approximate L2 Index with HNSW using node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an approximate nearest neighbor (ANN) index using the Hierarchical Navigable Small World (HNSW) algorithm for L2 distance with node-postgres. This speeds up similarity searches. ```javascript await client.query('CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)'); ``` -------------------------------- ### Insert vectors into items table with Objection.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Prepare and insert new items with vector embeddings into the 'items' table. Uses pgvector.toSql to format the vector data. ```javascript const newItems = [ {embedding: pgvector.toSql([1, 2, 3])}, {embedding: pgvector.toSql([4, 5, 6])} ]; await Item.query().insert(newItems); ``` -------------------------------- ### Import pgvector for Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Import the pgvector adapter specifically for use with Knex.js. This allows Knex.js to understand and use vector data types and operations. ```javascript import pgvector from 'pgvector/knex'; ``` -------------------------------- ### Query Nearest Neighbors with Bun SQL Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Perform a nearest neighbor search using Bun SQL. The `<->` operator signifies L2 distance. Ensure vectors are formatted using `pgvector.toSql()`. ```javascript const embedding = pgvector.toSql([1, 2, 3]); const items = await sql`SELECT * FROM items ORDER BY embedding <-> ${embedding} LIMIT 5`.values(); ``` -------------------------------- ### Add Approximate L2 Index with HNSW using Knex.js Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Add an approximate nearest neighbor (ANN) index using HNSW for L2 distance on a vector column with Knex.js. This requires using raw SQL within the schema alteration. ```javascript await knex.schema.alterTable('items', function (table) { table.index(knex.raw('embedding vector_l2_ops'), 'index_name', 'hnsw'); }); ``` -------------------------------- ### Slonik: Insert Vector Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a single vector into a table using Slonik. Format the vector using `pgvector.toSql`. ```javascript const embedding = pgvector.toSql([1, 2, 3]); await pool.query(sql.unsafe`INSERT INTO items (embedding) VALUES (${embedding})`); ``` -------------------------------- ### Register Vector Types with node-postgres Client Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Register the custom vector types with a node-postgres client to enable proper handling of vector data. This must be done before interacting with vector columns. ```javascript import pgvector from 'pgvector/pg'; await pgvector.registerTypes(client); ``` -------------------------------- ### Register pgvector types with pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Configure pg-promise to register pgvector types upon client connection. This involves setting up `initOptions` and calling `pgvector.registerTypes`. ```javascript import pgpromise from 'pg-promise'; import pgvector from 'pgvector/pg-promise'; const initOptions = { async connect(e) { await pgvector.registerTypes(e.client); } }; const pgp = pgpromise(initOptions); ``` -------------------------------- ### Register pgvector types with Sequelize Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Register the necessary pgvector data types with Sequelize to enable vector column support. Requires importing Sequelize and pgvector. ```javascript import { Sequelize } from 'sequelize'; import pgvector from 'pgvector/sequelize'; pgvector.registerTypes(Sequelize); ``` -------------------------------- ### Create Sparse Vector from Map Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create a `SparseVector` object using a map where keys are indices and values are the non-zero elements. You can also specify the total dimensions. ```javascript const vec = new SparseVector({0: 1, 2: 2, 4: 3}, 6); // or const map = new Map(); map.set(0, 1); map.set(2, 2); map.set(4, 3); const vec = new SparseVector(map, 6); ``` -------------------------------- ### Create Sparse Vector from Array Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Instantiate a `SparseVector` object from a dense array representation. Only non-zero elements are stored, making it efficient for sparse data. ```javascript const vec = new SparseVector([1, 0, 2, 0, 3, 0]); ``` -------------------------------- ### Insert a vector using pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a vector into the 'items' table using pg-promise. The `pgvector.toSql` function is used to format the vector data for the query. ```javascript await db.none('INSERT INTO items (embedding) VALUES ($1)', [pgvector.toSql([1, 2, 3])]); ``` -------------------------------- ### Insert vectors into items table with Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert new items with vector embeddings into the 'items' table using Kysely. pgvector.toSql is used for formatting. ```javascript const newItems = [ {embedding: pgvector.toSql([1, 2, 3])}, {embedding: pgvector.toSql([4, 5, 6])} ]; await db.insertInto('items').values(newItems).execute(); ``` -------------------------------- ### Query Nearest Neighbors with Drizzle ORM Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Retrieve the nearest neighbors to a given vector using L2 distance. Supports other distance metrics like 'innerProduct', 'cosineDistance', 'l1Distance', 'hammingDistance', and 'jaccardDistance'. ```javascript import { l2Distance } from 'drizzle-orm'; const allItems = await db.select() .from(items) .orderBy(l2Distance(items.embedding, [1, 2, 3])) .limit(5); ``` -------------------------------- ### Prisma: Add Vector Column Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a 'vector' type column in your Prisma schema. Note that `prisma migrate dev` does not support pgvector indexes. ```prisma model Item { id Int @id @default(autoincrement()) embedding Unsupported("vector(3)")? } ``` -------------------------------- ### Add approximate HNSW index with Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create an HNSW index on the 'embedding' column for efficient similarity searches using Kysely. Specifies vector_l2_ops for L2 distance. ```javascript await db.schema.createIndex('index_name') .on('items') .using('hnsw') .expression(sql`embedding vector_l2_ops`) .execute(); ``` -------------------------------- ### Add approximate HNSW or IVF flat index with pg-promise Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Add an approximate nearest neighbor index to the 'embedding' column. Supports HNSW and IVF flat indexes, specifying 'vector_l2_ops' for L2 distance. ```javascript await db.none('CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)'); // or await db.none('CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)'); ``` -------------------------------- ### Slonik: Add Approximate Index (HNSW) Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Add an HNSW index to a vector column for efficient approximate nearest neighbor searches with Slonik. Use `vector_l2_ops` for Euclidean distance. ```javascript await pool.query(sql.unsafe`CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)`); ``` -------------------------------- ### Prisma: Insert Vector Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a vector into a pgvector column using Prisma. Use `pgvector.toSql` to format the array and cast it to `vector` in the SQL query. ```javascript const embedding = pgvector.toSql([1, 2, 3]) await prisma.$executeRaw`INSERT INTO items (embedding) VALUES (${embedding}::vector)` ``` -------------------------------- ### Create items table with vector column using Kysely Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table named 'items' with an auto-incrementing 'id' and a 'embedding' column of type vector with a dimension of 3 using Kysely's schema builder. ```javascript await db.schema.createTable('items') .addColumn('id', 'serial', (cb) => cb.primaryKey()) .addColumn('embedding', sql`vector(3)`) .execute(); ``` -------------------------------- ### MikroORM: Define Entity Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a MikroORM entity with a vector property. Use `VectorType` from `pgvector/mikro-orm` and specify the type in the `@Property` decorator. ```typescript import { VectorType } from 'pgvector/mikro-orm'; @Entity() class Item { @PrimaryKey() id: number; @Property({type: VectorType}) embedding: number[]; } ``` -------------------------------- ### Insert Vector using node-postgres Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert a vector into a table using node-postgres. The pgvector.toSql() function converts a JavaScript array into the SQL representation for vectors. ```javascript await client.query('INSERT INTO items (embedding) VALUES ($1)', [pgvector.toSql([1, 2, 3])]); ``` -------------------------------- ### Convert Sparse Vector to Array Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Convert the `SparseVector` back into a dense array representation, including zero values. ```javascript const arr = vec.toArray(); ``` -------------------------------- ### Insert Vectors with Drizzle ORM Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Insert new items with vector embeddings into the database using Drizzle ORM. Ensure the data format matches the defined schema. ```javascript const newItems = [ {embedding: [1, 2, 3]}, {embedding: [4, 5, 6]} ]; await db.insert(items).values(newItems); ``` -------------------------------- ### Insert a vector using Sequelize Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Create a new record in the 'Item' model with a vector embedding. Sequelize handles the conversion of the array to the vector type. ```javascript await Item.create({embedding: [1, 2, 3]}); ``` -------------------------------- ### Register Vector Types with node-postgres Pool Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Register the custom vector types for all new connections established by a node-postgres pool. This ensures consistent vector type handling across the application. ```javascript pool.on('connect', async function (client) { await pgvector.registerTypes(client); }); ``` -------------------------------- ### Define Vector Field with Drizzle ORM Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a table schema with a vector field using Drizzle ORM. Specify the dimensions required for your embeddings. Supports 'halfvec', 'bit', and 'sparsevec' types. ```javascript import { vector } from 'drizzle-orm/pg-core'; const items = pgTable('items', { id: serial('id').primaryKey(), embedding: vector('embedding', {dimensions: 3}) }); ``` -------------------------------- ### TypeORM: Insert Vector Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Save a new item with a vector embedding using TypeORM's repository pattern. The embedding is automatically handled by the 'vector' column type. ```javascript const itemRepository = AppDataSource.getRepository(Item); await itemRepository.save({embedding: [1, 2, 3]}); ``` -------------------------------- ### Add approximate HNSW index with Sequelize Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define an HNSW index for the 'embedding' column within the Sequelize model definition. Specifies 'hnsw' as the index type and 'vector_l2_ops' as the operator. ```javascript const Item = sequelize.define('Item', ..., { indexes: [ { fields: ['embedding'], using: 'hnsw', operator: 'vector_l2_ops' } ] }); ``` -------------------------------- ### TypeORM: Define Entity Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a TypeORM entity class with a 'vector' type column. The `embedding` property should be an array of numbers. ```typescript @Entity() class Item { @PrimaryGeneratedColumn() id: number @Column('vector', {length: 3}) embedding: number[] } ``` -------------------------------- ### Add a vector field to a Sequelize model Source: https://github.com/pgvector/pgvector-node/blob/master/README.md Define a Sequelize model 'Item' with an 'embedding' field of type DataTypes.VECTOR with a dimension of 3. ```javascript const Item = sequelize.define('Item', { embedding: { type: DataTypes.VECTOR(3) } }, ...); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.