Filters
Filters can be used to precisely refine search results. You can filter by properties as well as metadata, and you can combine multiple filters with and
or or
conditions to further narrow down the results.
Code
This example finds entries in "Movie" based on their similarity to the query vector, only from those released after 2010. It prints out the title and release year of the top 5 matches.
import weaviate
import weaviate.classes.query as wq
import os
from datetime import datetime
# Instantiate your client (not shown). e.g.:
# headers = {"X-Cohere-Api-Key": os.getenv("COHERE_APIKEY")} # Replace with your Cohere API key
# client = weaviate.connect_to_weaviate_cloud(..., headers=headers) or
# client = weaviate.connect_to_local(..., headers=headers)
# Define a function to call the endpoint and obtain embeddings
from typing import List
import os
import cohere
from cohere import Client as CohereClient
co_token = os.getenv("COHERE_APIKEY")
co = cohere.Client(co_token)
# Define a function to call the endpoint and obtain embeddings
def vectorize(cohere_client: CohereClient, texts: List[str]) -> List[List[float]]:
response = cohere_client.embed(
texts=texts, model="embed-multilingual-v3.0", input_type="search_document"
)
return response.embeddings
# Get the collection
movies = client.collections.get("MovieCustomVector")
# Perform query
response = movies.query.near_vector(
near_vector=query_vector,
limit=5,
return_metadata=wq.MetadataQuery(distance=True),
filters=wq.Filter.by_property("release_date").greater_than(datetime(2020, 1, 1))
)
# Inspect the response
for o in response.objects:
print(
o.properties["title"], o.properties["release_date"].year
) # Print the title and release year (note the release date is a datetime object)
print(
f"Distance to query: {o.metadata.distance:.3f}\n"
) # Print the distance of the object from the query
client.close()
Explain the code
This query is identical to that shown earlier for vector search, but with the addition of a filter. The filters
parameter here takes an instance of the Filter
class to set the filter conditions. The current query filters the results to only include those with a release year after 2010.
Example results
Oppenheimer 2023
Distance to query: 0.754
Everything Everywhere All at Once 2022
Distance to query: 0.778
Meg 2: The Trench 2023
Distance to query: 0.779
Eternals 2021
Distance to query: 0.787
John Wick: Chapter 4 2023
Distance to query: 0.790
Questions and feedback
If you have any questions or feedback, let us know in the user forum.