Skip to content

Commit 9aed76a

Browse files
Create vector-database.md
1 parent 34e8bd5 commit 9aed76a

File tree

1 file changed

+290
-0
lines changed

1 file changed

+290
-0
lines changed
Lines changed: 290 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
---
2+
categories:
3+
- docs
4+
- develop
5+
- stack
6+
- oss
7+
- rs
8+
- rc
9+
- oss
10+
- kubernetes
11+
- clients
12+
description: Understand how to use Redis as a vector database
13+
linkTitle: Vector database
14+
stack: true
15+
title: Redis as a vector database quick start guide
16+
weight: 3
17+
aliases: /develop/get-started/vector-database
18+
---
19+
20+
This quick start guide helps you to:
21+
22+
1. Understand what a vector database is
23+
2. Create a Redis vector database
24+
3. Create vector embeddings and store vectors
25+
4. Query data and perform a vector search
26+
27+
{{< note >}}This guide uses [RedisVL]({{< relref "/develop/clients/redis-vl" >}}),
28+
which is a Python client library for Redis that is highly specialized for
29+
vector processing. You may also be interested in the vector query examples
30+
for our other client libraries:
31+
32+
- [`redis-py` (Python)]({{< relref "/develop/clients/redis-py/vecsearch" >}})
33+
- [`NRedisStack`(C#/.NET)]({{< relref "/develop/clients/dotnet/vecsearch" >}})
34+
- [`node-redis` (JavaScript/Node.js)]({{< relref "/develop/clients/nodejs/vecsearch" >}})
35+
- [`jedis` (Java)]({{< relref "/develop/clients/jedis/vecsearch" >}})
36+
- [`go-redis` (Go)]({{< relref "/develop/clients/go/vecsearch" >}})
37+
{{< /note >}}
38+
39+
## Understand vector databases
40+
41+
Data is often unstructured, which means that it isn't described by a well-defined schema. Examples of unstructured data include text passages, images, videos, or audio. One approach to storing and searching through unstructured data is to use vector embeddings.
42+
43+
**What are vectors?** In machine learning and AI, vectors are sequences of numbers that represent data. They are the inputs and outputs of models, encapsulating underlying information in a numerical form. Vectors transform unstructured data, such as text, images, videos, and audio, into a format that machine learning models can process.
44+
45+
- **Why are they important?** Vectors capture complex patterns and semantic meanings inherent in data, making them powerful tools for a variety of applications. They allow machine learning models to understand and manipulate unstructured data more effectively.
46+
- **Enhancing traditional search.** Traditional keyword or lexical search relies on exact matches of words or phrases, which can be limiting. In contrast, vector search, or semantic search, leverages the rich information captured in vector embeddings. By mapping data into a vector space, similar items are positioned near each other based on their meaning. This approach allows for more accurate and meaningful search results, as it considers the context and semantic content of the query rather than just the exact words used.
47+
48+
49+
## Create a Redis vector database
50+
You can use [Redis Stack]({{< relref "/operate/oss_and_stack/" >}}) as a vector database. It allows you to:
51+
52+
* Store vectors and the associated metadata within hashes or [JSON]({{< relref "/develop/data-types/json" >}}) documents
53+
* Create and configure secondary indices for search
54+
* Perform vector searches
55+
* Update vectors and metadata
56+
* Delete and cleanup
57+
58+
The easiest way to get started is to use Redis Cloud:
59+
60+
1. Create a [free account](https://redis.com/try-free?utm_source=redisio&utm_medium=referral&utm_campaign=2023-09-try_free&utm_content=cu-redis_cloud_users).
61+
62+
<img src="../img/free-cloud-db.png" width="500px">
63+
2. Follow the instructions to create a free database.
64+
65+
This free Redis Cloud database comes out of the box with all the Redis Stack features.
66+
67+
You can alternatively use the [installation guides]({{< relref "/operate/oss_and_stack/install/install-stack/" >}}) to install Redis Stack on your local machine.
68+
69+
You need to have the following features configured for your Redis server: JSON and Search and query.
70+
71+
## Install the required Python packages
72+
73+
Create a Python virtual environment and install the following dependencies using `pip`:
74+
75+
* `redis`: You can find further details about the `redis-py` client library in the [clients]({{< relref "/develop/clients/redis-py" >}}) section of this documentation site.
76+
* `pandas`: Pandas is a data analysis library.
77+
* `sentence-transformers`: You will use the [SentenceTransformers](https://www.sbert.net/) framework to generate embeddings on full text.
78+
* `tabulate`: `pandas` uses `tabulate` to render Markdown.
79+
80+
You will also need the following imports in your Python code:
81+
82+
{{< clients-example search_vss imports />}}
83+
84+
## Connect
85+
86+
Connect to Redis. By default, Redis returns binary responses. To decode them, you pass the `decode_responses` parameter set to `True`:
87+
88+
{{< clients-example search_vss connect />}}
89+
<br/>
90+
{{% alert title="Tip" color="warning" %}}
91+
Instead of using a local Redis Stack server, you can copy and paste the connection details from the Redis Cloud database configuration page. Here is an example connection string of a Cloud database that is hosted in the AWS region `us-east-1` and listens on port 16379: `redis-16379.c283.us-east-1-4.ec2.cloud.redislabs.com:16379`. The connection string has the format `host:port`. You must also copy and paste the username and password of your Cloud database. The line of code for connecting with the default user changes then to `client = redis.Redis(host="redis-16379.c283.us-east-1-4.ec2.cloud.redislabs.com", port=16379, password="your_password_here", decode_responses=True)`.
92+
{{% /alert %}}
93+
94+
95+
## Prepare the demo dataset
96+
97+
This quick start guide also uses the **bikes** dataset. Here is an example document from it:
98+
99+
```json
100+
{
101+
"model": "Jigger",
102+
"brand": "Velorim",
103+
"price": 270,
104+
"type": "Kids bikes",
105+
"specs": {
106+
"material": "aluminium",
107+
"weight": "10"
108+
},
109+
"description": "Small and powerful, the Jigger is the best ride for the smallest of tikes! ..."
110+
}
111+
```
112+
113+
The `description` field contains free-form text descriptions of bikes and will be used to create vector embeddings.
114+
115+
116+
### 1. Fetch the demo data
117+
You need to first fetch the demo dataset as a JSON array:
118+
119+
{{< clients-example search_vss get_data />}}
120+
121+
Inspect the structure of one of the bike JSON documents:
122+
123+
{{< clients-example search_vss dump_data />}}
124+
125+
### 2. Store the demo data in Redis
126+
Now iterate over the `bikes` array to store the data as [JSON]({{< relref "/develop/data-types/json/" >}}) documents in Redis by using the [JSON.SET]({{< relref "commands/json.set/" >}}) command. The below code uses a [pipeline]({{< relref "/develop/use/pipelining" >}}) to minimize the network round-trip times:
127+
128+
{{< clients-example search_vss load_data />}}
129+
130+
Once loaded, you can retrieve a specific attribute from one of the JSON documents in Redis using a [JSONPath](https://goessner.net/articles/JsonPath/) expression:
131+
132+
{{< clients-example search_vss get />}}
133+
134+
### 3. Select a text embedding model
135+
136+
[HuggingFace](https://huggingface.co) has a large catalog of text embedding models that are locally servable through the `SentenceTransformers` framework. Here we use the [MS MARCO](https://microsoft.github.io/msmarco/) model that is widely used in search engines, chatbots, and other AI applications.
137+
138+
```python
139+
from sentence_transformers import SentenceTransformer
140+
141+
embedder = SentenceTransformer('msmarco-distilbert-base-v4')
142+
```
143+
144+
### 4. Generate text embeddings
145+
Iterate over all the Redis keys with the prefix `bikes:`:
146+
147+
{{< clients-example search_vss get_keys />}}
148+
149+
Use the keys as input to the [JSON.MGET]({{< relref "commands/json.mget/" >}}) command, along with the `$.description` field, to collect the descriptions in a list. Then, pass the list of descriptions to the `.encode()` method:
150+
151+
{{< clients-example search_vss generate_embeddings />}}
152+
153+
Insert the vectorized descriptions to the bike documents in Redis using the [JSON.SET]({{< relref "commands/json.set" >}}) command. The following command inserts a new field into each of the documents under the JSONPath `$.description_embeddings`. Once again, do this using a pipeline to avoid unnecessary network round-trips:
154+
155+
{{< clients-example search_vss load_embeddings />}}
156+
157+
Inspect one of the updated bike documents using the [JSON.GET]({{< relref "commands/json.get" >}}) command:
158+
159+
{{< clients-example search_vss dump_example />}}
160+
161+
{{% alert title="Note" color="warning" %}}
162+
When storing a vector embedding within a JSON document, the embedding is stored as a JSON array. In the example above, the array was shortened considerably for the sake of readability.
163+
{{% /alert %}}
164+
165+
166+
## Create an index
167+
168+
### 1. Create an index with a vector field
169+
170+
You must create an index to query document metadata or to perform vector searches. Use the [FT.CREATE]({{< relref "commands/ft.create" >}}) command:
171+
172+
{{< clients-example search_vss create_index >}}
173+
FT.CREATE idx:bikes_vss ON JSON
174+
PREFIX 1 bikes: SCORE 1.0
175+
SCHEMA
176+
$.model TEXT WEIGHT 1.0 NOSTEM
177+
$.brand TEXT WEIGHT 1.0 NOSTEM
178+
$.price NUMERIC
179+
$.type TAG SEPARATOR ","
180+
$.description AS description TEXT WEIGHT 1.0
181+
$.description_embeddings AS vector VECTOR FLAT 6 TYPE FLOAT32 DIM 768 DISTANCE_METRIC COSINE
182+
{{< /clients-example >}}
183+
184+
Here is a breakdown of the `VECTOR` field definition:
185+
186+
* `$.description_embeddings AS vector`: The vector field's JSON path and its field alias `vector`.
187+
* `FLAT`: Specifies the indexing method, which is either a flat index or a hierarchical navigable small world graph ([HNSW](https://arxiv.org/ftp/arxiv/papers/1603/1603.09320.pdf)).
188+
* `TYPE FLOAT32`: Sets the float precision of a vector component, in this case a 32-bit floating point number.
189+
* `DIM 768`: The length or dimension of the embeddings, determined by the chosen embedding model.
190+
* `DISTANCE_METRIC COSINE`: The chosen distance function: [cosine distance](https://en.wikipedia.org/wiki/Cosine_similarity).
191+
192+
You can find further details about all these options in the [vector reference documentation]({{< relref "/develop/interact/search-and-query/advanced-concepts/vectors" >}}).
193+
194+
### 2. Check the state of the index
195+
196+
As soon as you execute the [FT.CREATE]({{< relref "commands/ft.create" >}}) command, the indexing process runs in the background. In a short time, all JSON documents should be indexed and ready to be queried. To validate that, you can use the [FT.INFO]({{< relref "commands/ft.info" >}}) command, which provides details and statistics about the index. Of particular interest are the number of documents successfully indexed and the number of failures:
197+
198+
{{< clients-example search_vss validate_index >}}
199+
FT.INFO idx:bikes_vss
200+
{{< /clients-example >}}
201+
202+
## Perform vector searches
203+
204+
This quick start guide focuses on vector search. However, you can learn more about how to query based on document metadata in the [document database quick start guide]({{< relref "/develop/get-started/document-database" >}}).
205+
206+
### 1. Embed your queries
207+
208+
The following code snippet shows a list of text queries you will use to perform vector search in Redis:
209+
210+
{{< clients-example search_vss def_bulk_queries />}}
211+
212+
First, encode each input query as a vector embedding using the same SentenceTransformers model:
213+
214+
{{< clients-example search_vss enc_bulk_queries />}}
215+
216+
<br/>
217+
{{% alert title="Tip" color="warning" %}}
218+
It is vital that you use the same embedding model to embed your queries as you did your documents. Using a different model will result in poor semantic search results or error.
219+
{{% /alert %}}
220+
221+
### 2. K-nearest neighbors (KNN) search
222+
The KNN algorithm calculates the distance between the query vector and each vector in Redis based on the chosen distance function. It then returns the top K items with the smallest distances to the query vector. These are the most semantically similar items.
223+
224+
Now construct a query to do just that:
225+
226+
```python
227+
query = (
228+
Query('(*)=>[KNN 3 @vector $query_vector AS vector_score]')
229+
.sort_by('vector_score')
230+
.return_fields('vector_score', 'id', 'brand', 'model', 'description')
231+
.dialect(2)
232+
)
233+
```
234+
235+
Let's break down the above query template:
236+
- The filter expression `(*)` means `all`. In other words, no filtering was applied. You could replace it with an expression that filters by additional metadata.
237+
- The `KNN` part of the query searches for the top 3 nearest neighbors.
238+
- The query vector must be passed in as the param `query_vector`.
239+
- The distance to the query vector is returned as `vector_score`.
240+
- The results are sorted by this `vector_score`.
241+
- Finally, it returns the fields `vector_score`, `id`, `brand`, `model`, and `description` for each result.
242+
243+
{{% alert title="Note" color="warning" %}}
244+
To utilize a vector query with the [`FT.SEARCH`]({{< relref "commands/ft.search/" >}}) command, you must specify DIALECT 2 or greater.
245+
{{% /alert %}}
246+
247+
You must pass the vectorized query as a byte array with the param name `query_vector`. The following code creates a Python NumPy array from the query vector and converts it into a compact, byte-level representation that can be passed as a parameter to the query:
248+
249+
```python
250+
client.ft('idx:bikes_vss').search(
251+
query,
252+
{
253+
'query_vector': np.array(encoded_query, dtype=np.float32).tobytes()
254+
}
255+
).docs
256+
```
257+
258+
With the template for the query in place, you can execute all queries in a loop. Notice that the script calculates the `vector_score` for each result as `1 - doc.vector_score`. Because the cosine distance is used as the metric, the items with the smallest distance are closer and, therefore, more similar to the query.
259+
260+
Then, loop over the matched documents and create a list of results that can be converted into a Pandas table to visualize the results:
261+
262+
{{< clients-example search_vss define_bulk_query />}}
263+
264+
The query results show the individual queries' top three matches (our K parameter) along with the bike's id, brand, and model for each query.
265+
266+
For example, for the query "Best Mountain bikes for kids", the highest similarity score (`0.54`) and, therefore the closest match was the 'Nord' brand 'Chook air 5' bike model, described as:
267+
268+
> The Chook Air 5 gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. The lower top tube makes it easy to mount and dismount in any situation, giving your kids greater safety on the trails. The Chook Air 5 is the perfect intro to mountain biking.
269+
270+
From the description, this bike is an excellent match for younger children, and the embeddings accurately captured the semantics of the description.
271+
272+
{{< clients-example search_vss run_knn_query />}}
273+
274+
| query | score | id | brand | model | description |
275+
| :--- | :--- | :--- | :--- | :--- | :--- |
276+
| Best Mountain bikes for kids | 0.54 | bikes:003 | Nord | Chook air 5 | The Chook Air 5 gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. The lower top tube makes it easy to mount and dismount in any situation, giving your kids greater safety on the trails. The Chook Air 5 is the perfect intro to mountain biking. |
277+
| | 0.51 | bikes:010 | nHill | Summit | This budget mountain bike from nHill performs well both on bike paths and on the trail. The fork with 100mm of travel absorbs rough terrain. Fat Kenda Booster tires give you grip in corners and on wet trails. The Shimano Tourney drivetrain offered enough gears for finding a comfortable pace to ride uphill, and the Tektro hydraulic disc brakes break smoothly. Whether you want an affordable bike that you can take to work, but also take trail riding on the weekends or you’re just after a stable,... |
278+
| | 0.46 | bikes:001 | Velorim | Jigger | Small and powerful, the Jigger is the best ride for the smallest of tikes! This is the tiniest kids’ pedal bike on the market available without a coaster brake, the Jigger is the vehicle of choice for the rare tenacious little rider raring to go. We say rare because this smokin’ little bike is not ideal for a nervous first-time rider, but it’s a true giddy up for a true speedster. The Jigger is a 12 inch lightweight kids bicycle and it will meet your little one’s need for speed. It’s a single... |
279+
280+
281+
## Next steps
282+
283+
1. You can learn more about the query options, such as filters and vector range queries, by reading the [vector reference documentation]({{< relref "/develop/interact/search-and-query/advanced-concepts/vectors" >}}).
284+
2. The complete [Redis Query Engine documentation]({{< relref "/develop/interact/search-and-query/" >}}) might be interesting for you.
285+
3. If you want to follow the code examples more interactively, then you can use the [Jupyter notebook](https://github.com/RedisVentures/redis-vss-getting-started/blob/main/vector_similarity_with_redis.ipynb) that inspired this quick start guide.
286+
4. If you want to see more advanced examples of a Redis vector database in action, visit the [Redis AI Resources](https://github.com/redis-developer/redis-ai-resources) page on GitHub.
287+
288+
## Continue learning with Redis University
289+
290+
{{< university-links >}}

0 commit comments

Comments
 (0)