Skip to main content

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-OpenAI-Api-Key": os.getenv("OPENAI_APIKEY")} # Replace with your OpenAI API key
# client = weaviate.connect_to_wcs(..., headers=headers) or
# client = weaviate.connect_to_local(..., headers=headers)

# Define a function to call the endpoint and obtain embeddings
def query(texts):
import requests
import os

model_id = "sentence-transformers/all-MiniLM-L6-v2"
hf_token = os.getenv("HUGGINGFACE_APIKEY")

api_url = f"https://api-inference.huggingface.co/pipeline/feature-extraction/{model_id}"
headers = {"Authorization": f"Bearer {hf_token}"}

response = requests.post(
api_url,
headers=headers,
json={"inputs": texts, "options": {"wait_for_model": True}},
)
return response.json()


# Get the collection
movies = client.collections.get("Movie")

# 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, please let us know on our forum. For example, you can: