|
| 1 | +# pgvector-node |
| 2 | + |
| 3 | +[pgvector](https://github.com/ankane/pgvector) support for Node.js |
| 4 | + |
| 5 | +Supports [Sequelize](https://github.com/sequelize/sequelize) and [node-postgres](https://github.com/brianc/node-postgres) |
| 6 | + |
| 7 | +[](https://github.com/ankane/pgvector-node/actions) |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +Run: |
| 12 | + |
| 13 | +```sh |
| 14 | +npm install pgvector |
| 15 | +``` |
| 16 | + |
| 17 | +And follow the instructions for your database library: |
| 18 | + |
| 19 | +- [Sequelize](#sequelize) |
| 20 | +- [node-postgres](#node-postgres) |
| 21 | + |
| 22 | +## Sequelize |
| 23 | + |
| 24 | +Register the type |
| 25 | + |
| 26 | +```js |
| 27 | +const { Sequelize } = require('sequelize'); |
| 28 | +const pgvector = require('pgvector/sequelize'); |
| 29 | + |
| 30 | +pgvector.registerType(Sequelize); |
| 31 | +``` |
| 32 | + |
| 33 | +Add a vector field |
| 34 | + |
| 35 | +```js |
| 36 | +Item.init({ |
| 37 | + factors: { |
| 38 | + type: DataTypes.VECTOR(3) |
| 39 | + } |
| 40 | +}, ...); |
| 41 | +``` |
| 42 | + |
| 43 | +Insert a vector |
| 44 | + |
| 45 | +```js |
| 46 | +await Item.create({factors: [1, 2, 3]}); |
| 47 | +``` |
| 48 | + |
| 49 | +Get the nearest neighbors to a vector |
| 50 | + |
| 51 | +```js |
| 52 | +const items = await Item.findAll({ |
| 53 | + order: [sequelize.literal(`factors <-> '[1, 2, 3]'`)], |
| 54 | + limit: 5 |
| 55 | +}); |
| 56 | +``` |
| 57 | + |
| 58 | +## node-postgres |
| 59 | + |
| 60 | +Register the type |
| 61 | + |
| 62 | +```js |
| 63 | +const pgvector = require('pgvector/pg'); |
| 64 | + |
| 65 | +await pgvector.registerType(client); |
| 66 | +``` |
| 67 | + |
| 68 | +Insert a vector |
| 69 | + |
| 70 | +```js |
| 71 | +const factors = [1, 2, 3]; |
| 72 | +await client.query('INSERT INTO items (factors) VALUES ($1)', [pgvector.toSql(factors)]); |
| 73 | +``` |
| 74 | + |
| 75 | +Get the nearest neighbors to a vector |
| 76 | + |
| 77 | +```js |
| 78 | +const result = await client.query('SELECT * FROM items ORDER BY factors <-> $1 LIMIT 5', [pgvector.toSql(factors)]); |
| 79 | +``` |
| 80 | + |
| 81 | +## History |
| 82 | + |
| 83 | +View the [changelog](https://github.com/ankane/pgvector-node/blob/master/CHANGELOG.md) |
| 84 | + |
| 85 | +## Contributing |
| 86 | + |
| 87 | +Everyone is encouraged to help improve this project. Here are a few ways you can help: |
| 88 | + |
| 89 | +- [Report bugs](https://github.com/ankane/pgvector-node/issues) |
| 90 | +- Fix bugs and [submit pull requests](https://github.com/ankane/pgvector-node/pulls) |
| 91 | +- Write, clarify, or fix documentation |
| 92 | +- Suggest or add new features |
| 93 | + |
| 94 | +To get started with development: |
| 95 | + |
| 96 | +```sh |
| 97 | +git clone https://github.com/ankane/pgvector-node.git |
| 98 | +cd pgvector-node |
| 99 | +npm install |
| 100 | +npm test |
| 101 | +``` |
0 commit comments