Filters
This lesson is currently being updated. Please check back soon for the latest version.
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 "MovieMM" based on their similarity to the query "dystopian future", 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-OpenAI-Api-Key": os.getenv("OPENAI_APIKEY")} # Replace with your OpenAI API key
# client = weaviate.connect_to_local(headers=headers)
# Configure collection object
movies = client.collections.use("MovieMM")
# Perform query
response = movies.query.near_text(
query="dystopian future",
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 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
Dune 2021
Distance to query: 0.199
Tenet 2020
Distance to query: 0.200
Mission: Impossible - Dead Reckoning Part One 2023
Distance to query: 0.207
Onward 2020
Distance to query: 0.214
Jurassic World Dominion 2022
Distance to query: 0.216