Keyword & Hybrid search
You can also perform keyword (BM25) searches to find items based on their keyword similarity, or hybrid searches that combine BM25 and semantic/vector searches.
Keyword search
Code
This example finds entries in "MovieMM" with the highest keyword search scores for the term "history", and prints out the title and release year of the top 5 matches.
import weaviate
import weaviate.classes.query as wq
import os
# 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)
# Get the collection
movies = client.collections.get("MovieMM")
# Perform query
response = movies.query.bm25(
query="history", limit=5, return_metadata=wq.MetadataQuery(score=True)
)
# 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"BM25 score: {o.metadata.score:.3f}\n"
) # Print the BM25 score of the object from the query
client.close()
Explain the code
The results are based on a keyword search score using what's called the BM25f algorithm.
The limit
parameter here sets the maximum number of results to return.
The return_metadata
parameter takes an instance of the MetadataQuery
class to set metadata to return in the search results. The current query returns the score
, which is the BM25 score of the result.
Example results
Hybrid search
Code
This example finds entries in "MovieMM" with the highest hybrid search scores for the term "history", and prints out the title and release year of the top 5 matches.
import weaviate
import weaviate.classes.query as wq
import os
# 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)
# Get the collection
movies = client.collections.get("MovieMM")
# Perform query
response = movies.query.hybrid(
query="history", limit=5, return_metadata=wq.MetadataQuery(score=True)
)
# 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"Hybrid score: {o.metadata.score:.3f}\n"
) # Print the hybrid search score of the object from the query
client.close()
Explain the code
The results are based on a hybrid search score. A hybrid search blends results of BM25 and semantic/vector searches.
The limit
parameter here sets the maximum number of results to return.
The return_metadata
parameter takes an instance of the MetadataQuery
class to set metadata to return in the search results. The current query returns the score
, which is the hybrid score of the result.
Example results
Questions and feedback
If you have any questions or feedback, let us know in the user forum.