如何在JavaScript中创建向量嵌入的blob表示,以用于Redis向量相似性搜索

ffx8fchx  于 2023-04-19  发布在  Redis
关注(0)|答案(1)|浏览(151)

有了像[1,2,3,4]这样的向量嵌入,我可以使用NumPy库用Python创建一个blob字节表示,如下所示:

np.array([1,2,3,4]).astype(dtype=np.float32).tobytes()

这将创建如下所示的输出:

\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'

如何用JavaScript创建这样的blob字符串?

cbeh67ev

cbeh67ev1#

node-redis客户端https://github.com/redis/node-redis/blob/master/examples/search-knn.js

function float32Buffer(arr) {
  return Buffer.from(new Float32Array(arr).buffer);
}

// Add some sample data...
// https://redis.io/commands/hset/
await Promise.all([
  client.hSet('noderedis:knn:a', { v: float32Buffer([0.1, 0.1]) }),
  client.hSet('noderedis:knn:b', { v: float32Buffer([0.1, 0.2]) }),
  client.hSet('noderedis:knn:c', { v: float32Buffer([0.1, 0.3]) }),
  client.hSet('noderedis:knn:d', { v: float32Buffer([0.1, 0.4]) }),
]);
// Perform a K-Nearest Neighbors vector similarity search
// Documentation: https://redis.io/docs/stack/search/reference/vectors/#pure-knn-queries
const results = await client.ft.search('idx:knn-example', '*=>[KNN 4 @v $BLOB AS dist]', {
  PARAMS: {
    BLOB: float32Buffer([0.1, 0.1])
  },
  SORTBY: 'dist',
  DIALECT: 2,
  RETURN: ['dist']
});
console.log(JSON.stringify(results, null, 2));

相关问题