import { Client } from "topk-js";
import { text, keywordIndex, semanticIndex } from "topk-js/schema";
import { select, field, fn } from "topk-js/query";
const client = new Client({
apiKey: process.env.TOPK_API_KEY!,
region: "aws-us-east-1-elastica",
});
// Create a collection
await client.collections().create("books", {
title: text().required().index(keywordIndex()),
content: text().index(semanticIndex()),
});
// Upsert documents
await 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
const results = await client.collection("books").query(
select({
title: field("title"),
author: field("author"),
// Compute semantic similarity of content field with the query
similarity_score: fn.semanticSimilarity(
"content",
"What is the meaning of life?",
),
})
// Filter documents by metadata
.filter(field("rating").gte(3.0))
// Rank using the computed similarity score and rating
.sort(field("rating").mul(field("similarity_score")), false)
// Get top 10 highest ranked documents
.limit(10)
);