Before starting, make sure you have:
- Installed the TopK SDK (Installation guide)
- Obtained an API key from console.topk.io
What you’ll build
By the end of this guide, you’ll have a working search application that can:Step 1: Initialize the client
First, create a TopK client with your API key and chosen region.Replace
YOUR_TOPK_API_KEY with your actual API key from the console.Step 2: Create a collection
Create a collection calledbooks with a semantic index on the title field. This enables both semantic and keyword search.
What’s happening here?
text()- Defines a text field.required()- Makes the field mandatory for all documents.index(semantic_index())- Creates a semantic index with automatic embeddings
Step 3: Add documents
Insert some sample book documents into your collection. Each document must have an_id field.
The
upsert() method creates new documents or updates existing ones if a document with the same _id already exists.Step 4: Search your collection
Now perform a semantic search to find books related to “classic American novel”.Understanding the query
Let’s break down the query:select()- Defines which fields to return and computed expressionsfn.semantic_similarity()- Computes semantic similarity score between the field and query text.topk()- Sorts by the similarity score and limits results to top 10
Expected output
Scores are similarity values - higher means more relevant. The exact values may vary based on the embedding model.
Step 5: Add reranking (optional)
Improve result relevance by adding reranking to your query:.rerank() method uses TopK’s built-in reranking model to refine the results, improving precision for the top results.
Learn more about reranking options in the Reranking guide.
Step 6: Clean up (optional)
When you’re done experimenting, you can delete the collection:Complete example
Here’s the full code in one place:Next steps
Now that you’ve built your first search application, explore more advanced features:Schema design
Learn about field types, indexes, and schema validation
Advanced queries
Combine filters, keyword search, and semantic search
Vector search
Use custom embeddings for vector similarity search
Keyword search
Perform traditional text matching with BM25 scoring