This notebook takes you through a simple flow to download some data, embed it, and then index and search it using a selection of vector databases. This is a common requirement for customers who want to store and search our embeddings with their own data in a secure environment to support production use cases such as chatbots, topic modelling and more.
A vector database is a database made to store, manage and search embedding vectors. The use of embeddings to encode unstructured data (text, audio, video and more) as vectors for consumption by machine-learning models has exploded in recent years, due to the increasing effectiveness of AI in solving use cases involving natural language, image recognition and other unstructured forms of data. Vector databases have emerged as an effective solution for enterprises to deliver and scale these use cases.
Vector databases enable enterprises to take many of the embeddings use cases we've shared in this repo (question and answering, chatbot and recommendation services, for example), and make use of them in a secure, scalable environment. Many of our customers make embeddings solve their problems at small scale but performance and security hold them back from going into production - we see vector databases as a key component in solving that, and in this guide we'll walk through the basics of embedding text data, storing it in a vector database and using it for semantic search.
Setup: Import packages and set any required variables
Load data: Load a dataset and embed it using OpenAI embeddings
Redis
Setup: Set up the Redis-Py client. For more details go here
Index Data: Create the search index for vector search and hybrid search (vector + full-text search) on all available fields.
Search Data: Run a few example queries with various goals in mind.
Once you've run through this notebook you should have a basic understanding of how to setup and use vector databases, and can move on to more complex use cases making use of our embeddings.
Import the required libraries and set the embedding model that we'd like to use.
# We'll need to install the Redis client!pip install redis#Install wget to pull zip file!pip install wget
import openaifrom typing import List, Iteratorimport pandas as pdimport numpy as npimport osimport wgetfrom ast import literal_eval# Redis client library for Pythonimport redis# I've set this to our new embeddings model, this can be changed to the embedding model of your choiceEMBEDDING_MODEL="text-embedding-3-small"# Ignore unclosed SSL socket warnings - optional in case you get these errorsimport warningswarnings.filterwarnings(action="ignore", message="unclosed", category=ResourceWarning)warnings.filterwarnings("ignore", category=DeprecationWarning)
In this section we'll load embedded data that we've prepared previous to this session.
embeddings_url ='https://cdn.openai.com/API/examples/data/vector_database_wikipedia_articles_embedded.zip'# The file is ~700 MB so this will take some timewget.download(embeddings_url)
import zipfilewith zipfile.ZipFile("vector_database_wikipedia_articles_embedded.zip","r") as zip_ref: zip_ref.extractall("../data")
# Read vectors from strings back into a listarticle_df['title_vector'] = article_df.title_vector.apply(literal_eval)article_df['content_vector'] = article_df.content_vector.apply(literal_eval)# Set vector_id to be a stringarticle_df['vector_id'] = article_df['vector_id'].apply(str)
The next vector database covered in this tutorial is Redis. You most likely already know Redis. What you might not be aware of is the RediSearch module. Enterprises have been using Redis with the RediSearch module for years now across all major cloud providers, Redis Cloud, and on premise. Recently, the Redis team added vector storage and search capability to this module in addition to the features RediSearch already had.
Given the large ecosystem around Redis, there are most likely client libraries in the language you need. You can use any standard Redis client library to run RediSearch commands, but it's easiest to use a library that wraps the RediSearch API. Below are a few examples, but you can find more client libraries here.
In the below cells, we will walk you through using Redis as a vector database. Since many of you are likely already used to the Redis API, this should be familiar to most.
There are many ways to deploy Redis with RediSearch. The easiest way to get started is to use Docker, but there are are many potential options for deployment. For other deployment options, see the redis directory in this repo.
For this tutorial, we will use Redis Stack on Docker.
Start a version of Redis with RediSearch (Redis Stack) by running the following docker command
$cdredis$dockercomposeup-d
This also includes the RedisInsight GUI for managing your Redis database which you can view at http://localhost:8001 once you start the docker container.
You're all set up and ready to go! Next, we import and create our client for communicating with the Redis database we just created.
The below cells will show how to specify and create a search index in Redis. We will
Set some constants for defining our index like the distance metric and the index name
Define the index schema with RediSearch fields
Create the index
# ConstantsVECTOR_DIM=len(article_df['title_vector'][0]) # length of the vectorsVECTOR_NUMBER=len(article_df) # initial number of vectorsINDEX_NAME="embeddings-index"# name of the search indexPREFIX="doc"# prefix for the document keysDISTANCE_METRIC="COSINE"# distance metric for the vectors (ex. COSINE, IP, L2)
# Define RediSearch fields for each of the columns in the datasettitle = TextField(name="title")url = TextField(name="url")text = TextField(name="text")title_embedding = VectorField("title_vector","FLAT", {"TYPE": "FLOAT32","DIM": VECTOR_DIM,"DISTANCE_METRIC": DISTANCE_METRIC,"INITIAL_CAP": VECTOR_NUMBER, })text_embedding = VectorField("content_vector","FLAT", {"TYPE": "FLOAT32","DIM": VECTOR_DIM,"DISTANCE_METRIC": DISTANCE_METRIC,"INITIAL_CAP": VECTOR_NUMBER, })fields = [title, url, text, title_embedding, text_embedding]
# Check if index existstry: redis_client.ft(INDEX_NAME).info()print("Index already exists")except:# Create RediSearch Index redis_client.ft(INDEX_NAME).create_index(fields= fields,definition= IndexDefinition(prefix=[PREFIX], index_type=IndexType.HASH) )
Now that we have a search index, we can load documents into it. We will use the same documents we used in the previous examples. In Redis, either the Hash or JSON (if using RedisJSON in addition to RediSearch) data types can be used to store documents. We will use the HASH data type in this example. The below cells will show how to load documents into the index.
defindex_documents(client: redis.Redis, prefix: str, documents: pd.DataFrame): records = documents.to_dict("records")for doc in records: key =f"{prefix}:{str(doc['id'])}"# create byte vectors for title and content title_embedding = np.array(doc["title_vector"], dtype=np.float32).tobytes() content_embedding = np.array(doc["content_vector"], dtype=np.float32).tobytes()# replace list of floats with byte vectors doc["title_vector"] = title_embedding doc["content_vector"] = content_embedding client.hset(key, mapping= doc)
index_documents(redis_client, PREFIX, article_df)print(f"Loaded {redis_client.info()['db0']['keys']} documents in Redis search index with name: {INDEX_NAME}")
Loaded 25000 documents in Redis search index with name: embeddings-index
Now that we have a search index and documents loaded into it, we can run search queries. Below we will provide a function that will run a search query and return the results. Using this function we run a few queries that will show how you can utilize Redis as a vector database. Each example will demonstrate specific features to keep in mind when developing your search application with Redis.
Return Fields: You can specify which fields you want to return in the search results. This is useful if you only want to return a subset of the fields in your documents and doesn't require a separate call to retrieve documents. In the below example, we will only return the title field in the search results.
Hybrid Search: You can combine vector search with any of the other RediSearch fields for hybrid search such as full text search, tag, geo, and numeric. In the below example, we will combine vector search with full text search.
# For using OpenAI to generate query embeddingopenai.api_key = os.getenv("OPENAI_API_KEY", "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")results = search_redis(redis_client, 'modern art in Europe', k=10)
0. Museum of Modern Art (Score: 0.875)
1. Western Europe (Score: 0.867)
2. Renaissance art (Score: 0.864)
3. Pop art (Score: 0.86)
4. Northern Europe (Score: 0.855)
5. Hellenistic art (Score: 0.853)
6. Modernist literature (Score: 0.847)
7. Art film (Score: 0.843)
8. Central Europe (Score: 0.843)
9. European (Score: 0.841)
results = search_redis(redis_client, 'Famous battles in Scottish history', vector_field='content_vector', k=10)
0. Battle of Bannockburn (Score: 0.869)
1. Wars of Scottish Independence (Score: 0.861)
2. 1651 (Score: 0.853)
3. First War of Scottish Independence (Score: 0.85)
4. Robert I of Scotland (Score: 0.846)
5. 841 (Score: 0.844)
6. 1716 (Score: 0.844)
7. 1314 (Score: 0.837)
8. 1263 (Score: 0.836)
9. William Wallace (Score: 0.835)
The previous examples showed how run vector search queries with RediSearch. In this section, we will show how to combine vector search with other RediSearch fields for hybrid search. In the below example, we will combine vector search with full text search.
# search the content vector for articles about famous battles in Scottish history and only include results with Scottish in the titleresults = search_redis(redis_client,"Famous battles in Scottish history",vector_field="title_vector",k=5,hybrid_fields=create_hybrid_field("title", "Scottish") )
0. First War of Scottish Independence (Score: 0.892)
1. Wars of Scottish Independence (Score: 0.889)
2. Second War of Scottish Independence (Score: 0.879)
3. List of Scottish monarchs (Score: 0.873)
4. Scottish Borders (Score: 0.863)
# run a hybrid query for articles about Art in the title vector and only include results with the phrase "Leonardo da Vinci" in the textresults = search_redis(redis_client,"Art",vector_field="title_vector",k=5,hybrid_fields=create_hybrid_field("text", "Leonardo da Vinci") )# find specific mention of Leonardo da Vinci in the text that our full-text-search query returnedmention = [sentence for sentence in results[0].text.split("\n") if"Leonardo da Vinci"in sentence][0]mention
'In Europe, after the Middle Ages, there was a "Renaissance" which means "rebirth". People rediscovered science and artists were allowed to paint subjects other than religious subjects. People like Michelangelo and Leonardo da Vinci still painted religious pictures, but they also now could paint mythological pictures too. These artists also invented perspective where things in the distance look smaller in the picture. This was new because in the Middle Ages people would paint all the figures close up and just overlapping each other. These artists used nudity regularly in their art.'
For more example with Redis as a vector database, see the README and examples within the vector_databases/redis directory of this repository