Create an index

This Astra DB Serverless feature is currently in public preview. Development is ongoing, and the features and functionality are subject to change. Astra DB Serverless, and the use of such, is subject to the DataStax Preview Terms.

The Data API tables commands are available through HTTP and the clients.

If you use a client, tables commands are available only in client versions 2.0-preview or later. For more information, see Data API client upgrade guide.

Creates a new index for a column in a table in a Serverless (Vector) database.

To create an index on a vector column, see Create a vector index instead.

To manage indexes, your application token must have the same level of permissions that you need to manage tables.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

table.create_index(
  name: str,
  *,
  column: str,
  options: TableIndexOptions | dict[str, Any],
  if_not_exists: bool,
  table_admin_timeout_ms: int,
  request_timeout_ms: int,
  timeout_ms: int,
) -> None
table.createIndex(
  name: string,
  column: WSchema | string,
  options?: {
    ifNotExists?: boolean,
    options?: {
      ascii?: boolean,
      normalize?: boolean,
      caseSensitive?: boolean,
      timeout?: number | TimeoutDescriptor,
    },
  },
): Promise<void>
void createIndex(
  String indexName,
  String columnName
)
void createIndex(
  String indexName,
  String columnName,
  CreateIndexOptions indexOptions
)
void createIndex(
  String indexName,
  TableIndexDefinition indexDefinition,
  CreateIndexOptions indexOptions
)
curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "createIndex": {
    "name": "INDEX_NAME",
    "definition": {
      "column": "COLUMN_NAME",
      "options": {
        "ascii": BOOLEAN,
        "normalize": BOOLEAN,
        "caseSensitive": BOOLEAN
      }
    }
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • curl

Creates an index for the specified column.

Does not return anything.

Creates an index for the specified column.

Returns a promise that resolves once the operation completes.

Creates an index for the specified column.

Does not return anything.

Creates an index for the specified column.

If the command succeeds, the response indicates the success.

Example response:

{
  "status": {
    "ok": 1
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

name

str

The name of the index.

Index names must be unique within a keyspace.

column

str

The name of the table column on which to create the index.

You cannot create indexes based on map, list, or set columns. To create vector indexes based on vector columns, see Create a vector index.

The column name must use snake case (not camel case).

options

TableIndexOptions | dict | None

Specifies Index options for text and ascii types. If passed, it must be an instance of TableIndexOptions or an equivalent dictionary.

if_not_exists

bool | None

If True, and an index with the given name already exists in the keyspace, then the command succeeds and silently does nothing. In this case, no actual index creation takes place on the database.

If False (default), an error occurs if an index with the specified name already exists.

if_not_exists: True, does not check the type or content of any existing indexes. This parameter checks index names only.

This means that the command succeeds if the given index name is already in use, even if the type or indexed column is different.

table_admin_timeout_ms

int | None

A timeout, in milliseconds, to impose on the underlying API request. If not provided, the Table defaults apply. This parameter is aliased as request_timeout_ms and timeout_ms for convenience.

Name Type Summary

name

string

The name of the index.

Index names must be unique within a keyspace.

column

string

The name of the table column on which to create the index.

You cannot create indexes based on map, list, or set columns. To create vector indexes based on vector columns, see Create a vector index.

An error occurs if the given column is already indexed or isn’t an indexable type.

The column name must use snake case (not camel case).

options?

TableCreateIndexOptions

The options for this operation.

Options (TableCreateIndexOptions):

Name Type Summary

ifNotExists?

boolean

If true, and an index with the given name already exists in the keyspace, then the command succeeds and silently does nothing. In this case, no actual index creation takes place on the database.

If false (default), an error occurs if an index with the specified name already exists.

ifNotExists: true, does not check the type or content of any existing indexes. This parameter checks index names only.

This means that the command succeeds if the given index name is already in use, even if the type or indexed column is different.

options.ascii?

boolean

Whether to convert non-ASCII characters to their US-ASCII equivalent before indexing. The default is false. See Index options for text and ascii types.

options.normalize?

boolean

Whether to normalize Unicode characters and diacritics before indexing. The default is false. See Index options for text and ascii types.

options.caseSensitive?

boolean

Whether the index is case sensitive. The default is true. See Index options for text and ascii types.

timeout?

number | TimeoutDescriptor

The client-side timeout for this operation.

Name Type Summary

name

str

The name of the index.

Index names must be unique within a keyspace.

definition

TableIndexDefinition

Definition of the index to create. Requires the name of the column to index. For text and ascii columns, you can specify index options.

You cannot create indexes based on map, list, or set columns. To create vector indexes based on vector columns, see Create a vector index.

The column name must use snake case (not camel case).

options

CreateIndexOptions

A specialization of index creation options, including ifNotExists and timeout.

If ifNotExists(true), and an index with the given name already exists in the keyspace, then the command succeeds and silently does nothing. In this case, no actual index creation takes place on the database.

If ifNotExists(false) (default), an error occurs if an index with the specified name already exists.

ifNotExists(true), does not check the type or content of any existing indexes. This parameter checks index names only.

This means that the command succeeds if the given index name is already in use, even if the type or indexed column is different.

Name Type Summary

createIndex

command

The Data API command to create an index for a table in a Serverless (Vector) database. It acts as a container for all the attributes and settings required to create the index.

name

string

The name of the index.

Index names must be unique within a keyspace.

definition

object

Contains the column and options for the index.

definition.column

string

The name of the table column on which to create the index.

You cannot create indexes based on map, list, or set columns. To create vector indexes based on vector columns, see Create a vector index.

The column name must use snake case (not camel case).

definition.options.ascii

boolean

Whether to convert non-ASCII characters to their US-ASCII equivalent before indexing. The default is false. See Index options for text and ascii types.

definition.options.normalize

boolean

Whether to normalize Unicode characters and diacritics before indexing. The default is false. See Index options for text and ascii types.

definition.options.caseSensitive

boolean

Whether the index is case sensitive. The default is true. See Index options for text and ascii types.

Examples

The following examples demonstrate how to create an index.

  • Python

  • TypeScript

  • Java

  • curl

Create an index on a table column:

my_table.create_index("score_index", column="score")

Create an index on a text or ascii column with options:

my_table.create_index(
    "winner_index", column="winner",
    options=TableIndexOptions(
        ascii=False, normalize=True, case_sensitive=False,
    ),
)

Example:

Full script
from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")

from astrapy.constants import SortMode
from astrapy.info import (
    CreateTableDefinition,
    ColumnType,
)

my_table = database.create_table(
    "games",
    definition=(
        CreateTableDefinition.builder()
        .add_column("match_id", ColumnType.TEXT)
        .add_column("round", ColumnType.TINYINT)
        .add_vector_column("m_vector", dimension=3)
        .add_column("score", ColumnType.INT)
        .add_column("when", ColumnType.TIMESTAMP)
        .add_column("winner", ColumnType.TEXT)
        .add_set_column("fighters", ColumnType.UUID)
        .add_partition_by(["match_id"])
        .add_partition_sort({"round": SortMode.ASCENDING})
        .build()
    ),
)

from astrapy.info import TableIndexOptions

# create an index on a column
my_table.create_index(
    "score_index",
    column="score",
)

# create an index on a textual column, specifying indexing options
my_table.create_index(
    "winner_index",
    column="winner",
    options=TableIndexOptions(
        ascii=False,
        normalize=True,
        case_sensitive=False,
    ),
)
from astrapy.info import TableIndexOptions

# create an index on a column
my_table.create_index(
    "score_index",
    column="score",
)

# create an index on a textual column, specifying indexing options
my_table.create_index(
    "winner_index",
    column="winner",
    options=TableIndexOptions(
        ascii=False,
        normalize=True,
        case_sensitive=False,
    ),
)

Create an index on a table column:

await table.createIndex('score_idx', 'score');

By default, an error occurs if an index with the given name already exists in the keyspace.

To silently ignore existing indexes, use ifNotExists: true. If true, an index is created if there is no name collision. If an index with the given name already exists, the command silently does nothing (neither creates an index nor throws an error).

await table.createIndex('winner_idx', 'winner', {
  ifNotExists: true,
});

Create an index on a text or ascii column with options:

await table.createIndex('winner_idx', 'winner', {
  options: {
    ascii: true,
    normalize: true,
    caseSensitive: false,
  },
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, SomeRow } from '@datastax/astra-db-ts';

// Instantiate the client and connect to the database
const client = new DataAPIClient();
const db = client.db(process.env.CLIENT_DB_URL!, { token: process.env.CLIENT_DB_TOKEN! });

// Create table schema using bespoke Data API table definition syntax.
// For information about table definition and data types, see the documentation for createTable.
const TableDefinition = <const>{
  columns: {
    matchId: 'text'
    round: 'tinyint',
    mVector: { type: 'vector', dimension: 3 },
    score: 'int',
    when: 'timestamp',
    winner: 'text',
    fighters: { type: 'set', valueType: 'uuid' },
  },
  primaryKey: {
    partitionBy: ['matchId'],
    partitionSort: { round: 1 },
  },
} satisfies CreateTableDefinition;

(async function () {
    // Create an untyped table if a 'games' table doesn't already exist
  const table = await db.createTable<SomeRow>('games', { definition: TableDefinition, ifNotExists: true });

  // Create a secondary index on the 'score' column with default options.
  // Errors if a 'score_idx' index already exists in the working keyspace.
  await table.createIndex('score_idx', 'score');

  // Create a secondary index on the 'winner' column with case-insensitivity
  // Because 'ifNotExists: true', the command does not throw an error
  // if the working keyspace already has an index named 'winner_idx'.
  await table.createIndex('winner_idx', 'winner', {
    options: {
      caseSensitive: false,
    },
    ifNotExists: true,
  });

  // Case insensitive indexes ignore case when querying.
  // Insert a row with upper case and lower case characters,
  // and then query the row.
  // findOne returns a match because 'winner_idx' is case-insensitive.
  await table.insertOne({ matchId: '01', round: 0, winner: 'Gray Tist' });
  await table.findOne({ winner: 'gray tist' }).then(console.log);

  // Create a vector index on the 'mVector' column with cosine similarity (default).
  // Errors if an 'm_vector_idx' index already exists in the working keyspace.
  await table.createVectorIndex('m_vector_idx', 'mVector');

  // Create a vector index on the 'mVector' column with dot-product similarity.
  // Because 'ifNotExists: true', the command does not throw an error
  // if the working keyspace already has an index named 'm_vector_idx'.
  await table.createVectorIndex('m_vector_idx', 'mVector', {
    options: {
      metric: 'dot_product',
    },
    ifNotExists: true,
  });

  // Drop the index so you can recreate it with different options.
  await db.dropTableIndex('m_vector_idx');

  // Create the vector index with dot-product similarity and a source model.
  // For accurate searches, use a source model and metric that are compatible with your vectors.
  await table.createVectorIndex('m_vector_idx', 'mVector', {
    options: {
      metric: 'dot_product',
      sourceModel: 'ada002',
    },
  });

  // Vector indexes allow you to perform vector searches.
  // Insert a row with a vector, and then run a vector search on the table.
  await table.insertOne({ matchId: '01', round: 0, mVector: [0.2, -0.3, -0.5] });
  await table.findOne({}, { sort: { mVector: [0.2, -0.3, -0.5] } }).then(console.log);

  // Get detailed information about the indexes
  // Returns information like [{ name: 'score_idx', definition: { column: 'score', options: {} } }, ...]
  await table.listIndexes().then(console.log);

  // Get index names only.
  // Returns information like ['score_idx', 'winner_idx', 'm_vector_idx', ...]
  await table.listIndexes({ nameOnly: true }).then(console.log);

  // Drop an index from a database's working keyspace without checking if the index exists.
  // If there is no match, the command succeeds but does nothing.
  // If there is a match, the named index is deleted.
  await db.dropTableIndex('score_idx');

  // Drop an index from a database's working keyspace if the index exists.
  // Errors if there is no match.
  await db.dropTableIndex('score_idx', { ifExists: true });

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();
// Create a secondary index on the 'score' column with default options.
// Errors if a 'score_idx' index already exists in the working keyspace.
await table.createIndex('score_idx', 'score');

// Create a secondary index on the 'winner' column with case-insensitivity
// Because 'ifNotExists: true', the command does not throw an error
// if the working keyspace already has an index named 'winner_idx'.
await table.createIndex('winner_idx', 'winner', {
  options: {
    caseSensitive: false,
  },
  ifNotExists: true,
});

// Case insensitive indexes ignore case when querying.
// Insert a row with upper case and lower case characters,
// and then query the row.
// findOne returns a match because 'winner_idx' is case-insensitive.
await table.insertOne({ matchId: '01', round: 0, winner: 'Gray Tist' });
await table.findOne({ winner: 'gray tist' }).then(console.log);

Create an index on a table column:

// Expects index name and the column to index
tableGames.createIndex("score_index","score");

Create an index on a text or ascii column with options:

TableIndexDefinition definition = new TableIndexDefinition()
 .column("winner")
 .ascii(false)
 .caseSensitive(true)
 .normalize(false);

CreateIndexOptions options = new CreateIndexOptions()
  .ifNotExists(true)
  .timeout(Duration.ofSeconds(2));

tableGames
  .createIndex("winner_index", definition, options);

Example:

package com.datastax.astra.client.tables;

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.commands.options.CreateIndexOptions;
import com.datastax.astra.client.tables.definition.indexes.TableIndexDefinition;
import com.datastax.astra.client.tables.definition.rows.Row;

import java.time.Duration;

public class CreateIndex {
 public static void main(String[] args) {
   Database db = new DataAPIClient("token").getDatabase("endpoint");

   Table<Row> tableGames = db.getTable("games");

   tableGames.createIndex("score_index","score");

   TableIndexDefinition definition = new TableIndexDefinition()
     .column("winner")
     .ascii(true)  // only text or ascii
     .caseSensitive(true)
     .normalize(true);

   CreateIndexOptions options = new CreateIndexOptions()
     .ifNotExists(true)
     .timeout(Duration.ofSeconds(2));
   tableGames.createIndex("winner_index", definition, options);
 }
}

Create an index:

curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/ASTRA_DB_KEYSPACE/ASTRA_DB_TABLE" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "createIndex": {
    "name": "INDEX_NAME",
    "definition": {
      "column": "COLUMN_NAME",
      "options": {
        "normalize": true,
        "caseSensitive": false
      }
    }
  }
}'

Examples:

curl -sS -L -X POST "ASTRA_DB_API_ENDPOINT/api/json/v1/default_keyspace/students" \
--header "Token: ASTRA_DB_APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
  "createIndex": {
    "name": "index_metadata_students",
    "definition": {
      "column": "student_id",
      "options": {
        "ascii": true,
        "caseSensitive": false
      }
    }
  }
}'

Client reference

  • Python

  • TypeScript

  • Java

  • curl

For more information, see the client reference.

For more information, see the client reference.

For more information, see the client reference.

Client reference documentation is not applicable for HTTP.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | 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: +1 (650) 389-6000, info@datastax.com