forked from redis/node-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch-knn.js
91 lines (85 loc) · 2.39 KB
/
search-knn.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// This example demonstrates how to use RediSearch to index and query data
// stored in Redis hashes using vector similarity search.
//
// Inspired by RediSearch Python tests:
// https://github.com/RediSearch/RediSearch/blob/06e36d48946ea08bd0d8b76394a4e82eeb919d78/tests/pytests/test_vecsim.py#L96
import { createClient, SchemaFieldTypes, VectorAlgorithms } from 'redis';
const client = createClient();
await client.connect();
// Create an index...
try {
// Documentation: https://redis.io/docs/stack/search/reference/vectors/
await client.ft.create('idx:knn-example', {
v: {
type: SchemaFieldTypes.VECTOR,
ALGORITHM: VectorAlgorithms.HNSW,
TYPE: 'FLOAT32',
DIM: 2,
DISTANCE_METRIC: 'COSINE'
}
}, {
ON: 'HASH',
PREFIX: 'noderedis:knn'
});
} catch (e) {
if (e.message === 'Index already exists') {
console.log('Index exists already, skipped creation.');
} else {
// Something went wrong, perhaps RediSearch isn't installed...
console.error(e);
process.exit(1);
}
}
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));
// results:
// {
// "total": 4,
// "documents": [
// {
// "id": "noderedis:knn:a",
// "value": {
// "dist": "5.96046447754e-08"
// }
// },
// {
// "id": "noderedis:knn:b",
// "value": {
// "dist": "0.0513167381287"
// }
// },
// {
// "id": "noderedis:knn:c",
// "value": {
// "dist": "0.10557281971"
// }
// },
// {
// "id": "noderedis:knn:d",
// "value": {
// "dist": "0.142507016659"
// }
// }
// ]
// }
await client.quit();