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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Vector Similarity\n",
"## Adding Vector Fields"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"b'OK'"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import redis\n",
"from redis.commands.search.field import VectorField\n",
"from redis.commands.search.query import Query\n",
"\n",
"r = redis.Redis(host='localhost', port=36379)\n",
"\n",
"schema = (VectorField(\"v\", \"HNSW\", {\"TYPE\": \"FLOAT32\", \"DIM\": 2, \"DISTANCE_METRIC\": \"L2\"}),)\n",
"r.ft().create_index(schema)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Searching"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Querying vector fields"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"pycharm": {
"name": "#%%\n"
}
},
"outputs": [
{
"data": {
"text/plain": [
"Result{2 total, docs: [Document {'id': 'a', 'payload': None, '__v_score': '0'}, Document {'id': 'b', 'payload': None, '__v_score': '3.09485009821e+26'}]}"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"r.hset(\"a\", \"v\", \"aaaaaaaa\")\n",
"r.hset(\"b\", \"v\", \"aaaabaaa\")\n",
"r.hset(\"c\", \"v\", \"aaaaabaa\")\n",
"\n",
"q = Query(\"*=>[KNN 2 @v $vec]\").return_field(\"__v_score\").dialect(2)\n",
"r.ft().search(q, query_params={\"vec\": \"aaaaaaaa\"})"
]
}
],
"metadata": {
"interpreter": {
"hash": "d45c99ba0feda92868abafa8257cbb4709c97f1a0b5dc62bbeebdf89d4fad7fe"
},
"kernelspec": {
"display_name": "Python 3.8.12 64-bit ('venv': venv)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.2"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
|