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 "dystopian future", only from those released after 2010. It prints out the title and release year of the top 5 matches.

import weaviate, { WeaviateClient, WeaviateReturn } from "weaviate-client";
let client: WeaviateClient;
let response: WeaviateReturn<undefined>

// Instantiate your client (not shown). e.g.:
// const requestHeaders = {'X-VoyageAI-Api-Key': process.env.VOYAGEAI_API_KEY as string,}
// client = weaviate.connectToWeaviateCloud(..., headers: requestHeaders) or
// client = weaviate.connectToLocal(..., headers: requestHeaders)

async function urlToBase64(imageUrl: string) {
const response = await fetch(imageUrl);
const arrayBuffer = await response.arrayBuffer();
const content = Buffer.from(arrayBuffer);
return content.toString('base64');
}

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

// Perform query
const srcImgPath = "https://github.com/weaviate-tutorials/edu-datasets/blob/main/img/International_Space_Station_after_undocking_of_STS-132.jpg?raw=true"
const queryB64 = await urlToBase64(srcImgPath)

const filterTime = new Date(2010, 1, 1)

response = await movies.query.nearText("dystopian future", {
limit: 5,
returnMetadata: ['distance'],
filters: movies.filter.byProperty("release_date").greaterThan(filterTime)
}
)

// Inspect the response
for (let item of response.objects) {
// Print the title and release year (note the release date is a datetime object)
console.log(`${item.properties.title} - ${item.properties.release_date}`)
// Print the distance of the object from the query
console.log(`Distance to query: ${item.metadata?.distance}`)
}

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 makes use of the filter namespace 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

Questions and feedback

If you have any questions or feedback, let us know in the user forum.