Github Example: https://github.com/libraryofcelsus/Basic-Qdrant-Upload-and-Search-Example
Introduction #
In this tutorial, you’ll learn how to search for specific vectors within Qdrant Vector DB. The search process involves querying the database with an encoded vector and retrieving relevant results.
1. Initialize the Qdrant Client #
Before performing a search, we need to establish a connection with the Qdrant server. Our script will first determine if a local Qdrant server is running. If not, it will connect to the Qdrant server in the cloud using stored API key and URL values. These will be stored in .txt files in the same folder as the script.
# Check if local server is running
if check_local_server_running():
client = QdrantClient(url="http://localhost:6333")
print("Connected to local Qdrant server.")
else:
url = open_file('./qdrant_url.txt')
api_key = open_file('./qdrant_api_key.txt')
client = QdrantClient(url=url, api_key=api_key)
print("Connected to cloud Qdrant server.")
2. Vectorize and Search #
To search the Qdrant database, we need to convert our text query into a numerical vector (embedding). Once we have the vector, we’ll send it as a query to the database.
model = SentenceTransformer('all-mpnet-base-v2')
vector = model.encode([query])[0].tolist()
try:
hits = client.search(
collection_name=f"<<ENTER COLLECTION NAME>>",
query_vector=vector,
limit=5)
3. Process and Display Results #
The results from the database search will contain metadata. We’ll extract the message field from this metadata (or any other field you’re interested in) and display the results.
results = [hit.payload['message'] for hit in hits]
print(results)
4. Error Handling #
It’s always good practice to handle unexpected issues that might arise during execution. In our script, we’ll capture and display any errors encountered during the search process.
except Exception as e:
print(f"An unexpected error occurred: {str(e)}")