Hyper-Converged Database (HCD) quickstart for tables (TypeScript)

network_check Beginner
query_builder 15 min

If your data is not fully structured, or if you do not want to use a fixed schema, see the quickstart for collections instead.

This quickstart demonstrates how to create a table schema, insert data with vector embeddings to a table, and perform a vector search to find similar data.

To learn more about vector databases and vector search, see About vector databases and What is Vector Search.

Store your endpoint

The Data API endpoint for your database has the form: http://CLUSTER_HOST:GATEWAY_PORT

  • Replace CLUSTER_HOST with the external IP address of any node in your cluster. To find this, run kubectl get nodes -o wide and use any of the values listed under "EXTERNAL-IP" in the output.

  • Replace GATEWAY_PORT with the port number for your API gateway service. To find this, run kubectl get svc and look for the "PORT(S)" value that corresponds to NodePort.

For this quickstart, store the endpoint in an environment variable:

  • Linux or macOS

  • Windows

export API_ENDPOINT=API_ENDPOINT
set API_ENDPOINT=API_ENDPOINT

Store your username and password

You set a username and password when you create a cluster.

If you didn’t provide superuser credentials when you created your cluster, they were generated automatically and saved in a superuser secret named CLUSTER_NAME-superuser. The CLUSTER_NAME-superuser secret contains both the username and the password.

For this quickstart, store the username and password in environment variables:

  • Linux or macOS

  • Windows

export USERNAME=USERNAME
export PASSWORD=PASSWORD
set USERNAME=USERNAME
set PASSWORD=PASSWORD

Install a client

Install one of the Data API clients to facilitate interactions with the Data API. To use the Data API with tables, you must install client version 2.0.x.

  1. Update to Node version 18 or later if needed.

  2. Update to TypeScript version 5 or later if needed. This is unnecessary if you are using JavaScript instead of TypeScript.

  3. Install the latest version of the @datastax/astra-db-ts package.

    For example:

    npm install @datastax/astra-db-ts

Connect to your database

The following function will connect to your database.

Copy the file into your project. You don’t need to execute the function now; the subsequent code examples will import and use this function.

quickstart-connect.ts
import {
  DataAPIClient,
  Db,
  UsernamePasswordTokenProvider,
} from "@datastax/astra-db-ts";

/**
 * Connects to your database.
 * This function retrieves the database endpoint, username, and password from the
 * environment variables `API_ENDPOINT`, `USERNAME`, and `PASSWORD`.
 *
 * @returns An instance of the connected database.
 * @throws Will throw an error if the environment variables
 * `API_ENDPOINT`, `USERNAME`, or `PASSWORD` are not defined.
 */
export function connectToDatabase(): Db {
  const {
    API_ENDPOINT: endpoint,
    USERNAME: username,
    PASSWORD: password,
  } = process.env; (1)

  if (!endpoint || !username || !password) {
    throw new Error(
      "Environment variables API_ENDPOINT, USERNAME, and PASSWORD must be defined.",
    );
  }

  // Create an instance of the `DataAPIClient` class
  const client = new DataAPIClient({ environment: "hcd" });

  // Get the database specified by your endpoint and provide the token
  const database = client.db(endpoint, {
    token: new UsernamePasswordTokenProvider(username, password),
  });

  console.log("Connected to database");

  return database;
}
1 Store your database’s endpoint, username, and password in environment variables named API_ENDPOINT, USERNAME, and PASSWORD, as instructed in Store your endpoint and Store your username and password.

Create a keyspace

The following code will create a new keyspace in your database.

  1. Copy the code into your project.

  2. If needed, update the import path to the "connect to database" function from the previous section.

  3. Execute the code.

    For information about executing code, refer to the documentation for your programming language.

    Once the code completes, you should see a printed message confirming keyspace creation.

quickstart-create-keyspace.ts
import { connectToDatabase } from "./quickstart-connect"; (1)

(async function () {
  const database = connectToDatabase();

  // Get an admin object
  const admin = database.admin({ environment: "hcd" });

  // Create a keyspace
  await admin.createKeyspace("quickstart_keyspace"); (2)

  console.log("Created keyspace");
})();
1 This is the connectToDatabase function from the previous section. Update the import path if necessary.

To use the function, ensure you stored your database’s endpoint, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 This code creates a keyspace named quickstart_keyspace. If you want to use a different name, change the name before running the code.

Create a table

The following code will create an empty table in your database. The table created here matches the structure of the data that you will insert to the table. After creating the table, the code will index some columns so that you can find and sort data in those columns.

  1. Copy the code into your project.

  2. If needed, update the import path to the "connect to database" function from the previous section.

  3. Execute the code.

    For information about executing code, refer to the documentation for your programming language.

    Once the code completes, you should see a printed message confirming the table creation.

quickstart-create-table.ts
import { connectToDatabase } from "./quickstart-connect"; (1)
import {
  Table,
  InferTablePrimaryKey,
  InferTableSchema,
} from "@datastax/astra-db-ts";

const database = connectToDatabase();

const tableDefinition = Table.schema({
  // Define all of the columns in the table
  columns: {
    title: "text",
    author: "text",
    number_of_pages: "int",
    rating: "float",
    publication_year: "int",
    summary: "text",
    genres: { type: "set", valueType: "text" },
    metadata: {
      type: "map",
      keyType: "text",
      valueType: "text",
    },
    is_checked_out: "boolean",
    borrower: "text",
    due_date: "date",
    // This column will store vector embeddings. (2)
    summary_genres_vector: { type: "vector", dimension: 5 },
  },
  // Define the primary key for the table.
  // In this case, the table uses a composite primary key.
  primaryKey: {
    partitionBy: ["title", "author"],
  },
});

// Infer the TypeScript-equivalent type of the table's schema and primary key.
// Export the types for later use.
export type TableSchema = InferTableSchema<typeof tableDefinition>;
export type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;

(async function () {
  const table = await database.createTable<TableSchema, TablePrimaryKey>(
    "quickstart_table", (3)
    {
      definition: tableDefinition,
      keyspace: "quickstart_keyspace", (4)
    },
  );

  console.log("Created table");

  // Index any columns that you want to sort and filter on.
  await table.createIndex("rating_index", "rating");

  await table.createIndex("number_of_pages_index", "number_of_pages");

  await table.createVectorIndex(
    "summary_genres_vector_index",
    "summary_genres_vector",
    {
      options: {
        metric: "cosine", (5)
      },
    },
  );

  console.log("Indexed columns");
})();
1 This is the connectToDatabase function from the previous section. Update the import path if necessary.

To use the function, ensure you stored your database’s endpoint, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 This column will store 5-dimensional vector data.
3 This code creates a table named quickstart_table. If you want to use a different name, change the name before running the code.
4 This code expects that you have a keyspace named quickstart_keyspace. If you used a different keyspace name in the previous section, update it here.
5 This vector column will use the cosine similarity metric to compare vectors.

Insert data to your table

The following code will insert data from a JSON file into a your table.

  1. Copy the code into your project.

  2. Download the quickstart_dataset.json sample dataset (76 kB). This dataset is a JSON array describing library books.

  3. Replace PATH_TO_DATA_FILE in the code with the path to the dataset.

  4. If needed, update the import path to the "connect to database" function from the previous section.

  5. Execute the code.

    For information about executing code, refer to the documentation for your programming language.

    Once the code completes, you should see a printed message confirming the insertion of 100 rows.

quickstart-insert-to-table.ts
import { connectToDatabase } from "./quickstart-connect"; (1)
import { TableSchema, TablePrimaryKey } from "./quickstart-create-table"; (2)
import { DataAPIDate, DataAPIVector } from "@datastax/astra-db-ts";
import fs from "fs";

(async function () {
  const database = connectToDatabase();

  const table = database.table<TableSchema, TablePrimaryKey>(
    "quickstart_table",
    { keyspace: "quickstart_keyspace" },
  ); (3)

  const dataFilePath = "PATH_TO_DATA_FILE"; (4)

  // Read the JSON file and parse it into a JSON array.
  const rawData = fs.readFileSync(dataFilePath, "utf8");
  const jsonData = JSON.parse(rawData);

  const rows = jsonData.map((data: any) => ({
    ...data,
    genres: new Set(data.genres),
    metadata: new Map(Object.entries(data.metadata)),
    due_date: data.due_date ? new DataAPIDate(data.due_date) : null,
    summary_genres_vector: new DataAPIVector(data["summary_genres_vector"]),
  }));

  const insertedResult = await table.insertMany(rows);

  console.log(`Inserted ${insertedResult.insertedCount} rows.`);
})();
1 This is the connectToDatabase function from the previous section. Update the import path if necessary.

To use the function, ensure you stored your database’s endpoint, username, and password in environment variables as instructed in Store your endpoint and Store your username and password.

2 These are the types exported from the previous section. Update the import path if necessary.
3 This code expects that you have a table named quickstart_table in a keyspace named quickstart_keyspace. If you used a different keyspace or table name in the previous sections, update it here.
4 Replace PATH_TO_DATA_FILE with the path to the JSON data file.

Find data in your table

After you insert data to your table, you can search the data. In addition to traditional database filtering, you can perform a vector search to find data that is most similar to a search vector.

The following code performs three searches on the sample data that you loaded in Insert data to your table.

quickstart-find-rows.ts
import { connectToDatabase } from "./quickstart-connect"; (1)
import { TableSchema, TablePrimaryKey } from "./quickstart-create-table"; (2)

(async function () {
  const database = connectToDatabase();

  const table = database.table<TableSchema, TablePrimaryKey>(
    "quickstart_table",
    { keyspace: "quickstart_keyspace" },
  ); (3)

  // Find rows that match a filter
  console.log("\nFinding books with rating greater than 4.7...");

  const ratingCursor = table.find(
    { rating: { $gt: 4.7 } },
    {
      limit: 10,
      projection: { title: true, rating: true },
    },
  );

  for await (const row of ratingCursor) {
    console.log(`${row.title} is rated ${row.rating}`);
  }

  // Perform a vector search to find the closest match to a search vector
  console.log("\nUsing vector search to find a book...");

  const singleVectorMatch = await table.findOne(
    {},
    {
      sort: {
        summary_genres_vector: [
          0.016326904, -0.031677246, 0.04815674, 0.0033435822, 0.01876831,
        ],
      },
      projection: { title: true },
    },
  );

  console.log(`${singleVectorMatch?.title} is the best match`);

  // Combine a filter, vector search, and projection to find the 3 books with
  // more than 400 pages that are the closest matches to a search vector
  console.log(
    "\nUsing filters and vector search to find 3 books with more than 400 pages, returning just the title and author...",
  );

  const vectorCursor = table.find(
    { number_of_pages: { $gt: 400 } },
    {
      sort: {
        summary_genres_vector: [
          0.016326904, -0.031677246, 0.04815674, 0.0033435822, 0.01876831,
        ],
      },
      limit: 3,
      projection: { title: true, author: true },
    },
  );

  for await (const row of vectorCursor) {
    console.log(row);
  }
})();
1 This is the connectToDatabase function from the previous section. Update the import path if necessary.
2 These are the types exported from the previous section. Update the import path if necessary.
3 This code expects that you have a table named quickstart_table in a keyspace named quickstart_keyspace. If you used a different keyspace or table name in the previous sections, update it here.

Next steps

For more practice, you can continue building with the table that you created here. For example, try inserting more data to the table, or try different searches. The Data API reference provides code examples for various operations.

Insert data from different sources

This quickstart demonstrated how to insert structured data from a JSON file into a table, but you can insert data from many sources.

Tables use fixed schemas. If your data is unstructured or if you want a flexible schema, you can use a collection instead of a table. See the quickstart for collections.

Perform more complex searches

This quickstart demonstrated how to find data using filters and vector search. To learn more about the searches you can perform, see Find rows (TypeScript), Filter operators for tables (TypeScript), Sort clauses for tables (TypeScript), and Find data with vector search.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | Privacy policy | Terms of use Manage Privacy Choices

Apache, Apache Cassandra, Cassandra, Apache Tomcat, Tomcat, Apache Lucene, Apache Solr, Apache Hadoop, Hadoop, Apache Pulsar, Pulsar, Apache Spark, Spark, Apache TinkerPop, TinkerPop, Apache Kafka and Kafka are either registered trademarks or trademarks of the Apache Software Foundation or its subsidiaries in Canada, the United States and/or other countries. Kubernetes is the registered trademark of the Linux Foundation.

General Inquiries: Contact IBM