import os
from topk_sdk import Client
from topk_sdk.schema import text, keyword_index, semantic_index
from topk_sdk.query import select, field, fn
client = Client(
api_key=os.environ["TOPK_API_KEY"],
region="aws-us-east-1-elastica",
)
# Create a collection
client.collections().create(
"books",
schema={
"title": text().required().index(keyword_index()),
"content": text().index(semantic_index()),
},
)
# Upsert documents
client.collection("books").upsert([
{
"_id": "1",
"title": "Catcher in the Rye",
"content": "IF YOU REALLY WANT TO HEAR about it, the first thing you'll probably want to know is ...",
"author": "J.D. Salinger",
"rating": 3.8,
},
{
"_id": "2",
"title": "1984",
"content": "It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, ...",
"author": "George Orwell",
"rating": 4.7,
},
])
# Query with hybrid search
results = client.collection("books").query(
select(
# Select document fields to return
"_id", "title", "author",
# Compute semantic similarity of content field with the query
similarity_score=fn.semantic_similarity(
"content",
"What is the meaning of life?",
),
)
# Filter documents by metadata
.filter(field("rating") >= 3.0)
# Rank using the computed similarity score and rating
.sort(field("rating") * field("similarity_score"), asc=False)
# Get top 10 highest ranked documents
.limit(10)
)