Filters
In this lesson, you will learn how to use filters to refine your search results.
We covered the concepts of filters briefly in another course (Key Concepts & Architecture). Briefly, filters allow you to narrow down search results based on specific criteria, such as properties or metadata.
Here, you will see a practical example of how to filter data using the Python client and the previously ingested "Movies" data.
Code
Run this example to find entries in "Movies" based on their similarity to "dystopian future", as long as it was released after 2020. It prints out the title and release year of the top 5 matches.
import weaviate
from weaviate.classes.query import Filter, MetadataQuery
import os
from datetime import datetime
# Instantiate your client (not shown). e.g.:
# client = weaviate.connect_to_weaviate_cloud(...) or
# client = weaviate.connect_to_local(...)
# Configure collection object
movies = client.collections.use("Movies")
# Perform query
response = movies.query.near_text(
query="dystopian future",
limit=5,
return_metadata=MetadataQuery(distance=True),
filters=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
Filters 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.
This query is identical to an earlier example for semantic search, but with the addition of a filter. The filters parameter here takes Filter-based conditions. This query filters the results to only include those released after 2020.
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
Filters can be combined with any search types to limit results to only those that meet the filter criteria. Next, you will learn how to use retrievals to generate new content based on the search results.