Skip to main content
npm version The TopK JavaScript library provides convenient access to the TopK API from Node.js environments with full Typescript support.

Installation

npm install topk-js
# or
yarn add topk-js
# or
pnpm install topk-js

Prerequisites

Usage

import { Client } from "topk-js";
import { text, 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().index(semanticIndex()),
});

// Upsert documents
await client.collection("books").upsert([
  { _id: "gatsby", title: "The Great Gatsby" },
  { _id: "1984", title: "1984" },
]);

// Query
const results = await client.collection("books").query(
  select({
    title: field("title"),
    score: fn.semanticSimilarity("title", "classic American novel"),
  }).topk(field("score"), 10)
);

Handling errors

import { Client } from "topk-js";

const client = new Client({
  apiKey: process.env.TOPK_API_KEY,
  region: "aws-us-east-1-elastica",
});

try {
  await client.collection("books").query(...);
} catch (err: any) {
  console.error(err.message);
}
ErrorDescription
CollectionNotFoundErrorCollection does not exist
CollectionAlreadyExistsErrorCollection with this name already exists
CollectionValidationErrorInvalid collection name or schema
DocumentValidationErrorInvalid document
SchemaValidationErrorInvalid schema
PermissionDeniedErrorInvalid or missing API key
QuotaExceededErrorUsage quota exceeded
RequestTooLargeErrorRequest payload too large
SlowDownErrorRate limited by the server (retried automatically)
QueryLsnTimeoutErrorTimed out waiting for write consistency

Retries

The client automatically retries on SlowDownError and on LSN consistency timeouts. Retry behaviour can be configured via retryConfig:
import { Client } from "topk-js";

const client = new Client({
  apiKey: process.env.TOPK_API_KEY,
  region: "aws-us-east-1-elastica",
  retryConfig: {
    maxRetries: 5,       // default: 3
    timeout: 60_000,     // total retry chain timeout in ms, default: 30,000
    backoff: {
      initBackoff: 200,  // default: 100 ms
      maxBackoff: 5_000, // default: 10,000 ms
    },
  },
});

Requirements

Node.js 18 or higher.