Alter a table

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.

Alters a table by doing one of the following:

  • Adding one or more columns to a table

  • Dropping one or more columns from a table

  • Adding automatic embedding generation for one or more vector columns

  • Removing automatic embedding generation for one or more vector columns

You cannot change a column’s type. Instead, you must drop the column and add a new column.

Similarly, you cannot rename a table. Instead, you must drop and recreate the table.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

The following method belongs to the astrapy.Table class.

alter(
  operation: AlterTableOperation | dict[str, Any],
  *,
  row_type: type[Any] = DefaultRowType,
  table_admin_timeout_ms: int,
  request_timeout_ms: int,
  timeout_ms: int,
) -> Table[NEW_ROW]

The following method belongs to the Table class.

alter<NewWSchema extends SomeRow, NewRSchema extends SomeRow = FoundRow<NewWSchema>>(
  options: AlterTableOptions<SomeRow>
): Promise<Table<NewWSchema, PKey, NewRSchema>>

The following methods belong to the com.datastax.astra.client.tables.Table class.

Table<T> alter(AlterTableOperation operation)
Table<T> alter(
  AlterTableOperation operation,
  AlterTableOptions options
)
<R> Table<R> alter(
  AlterTableOperation operation,
  AlterTableOptions options,
  Class<R> clazz
)
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 '{
  "alterTable": {
    "operation": OPERATION
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • curl

Adds or drops columns, or adds or removes a vectorize integration for vector columns.

Removing a vectorize integration for a column does not change the column type or remove the vector embeddings stored in the column.

Returns a new Table instance that represents the table after the modification.

Although the Table instance that you used to perform the alteration will still work, it will not reflect the updated typing if you added or dropped columns.

Adds or drops columns, or adds or removes a vectorize integration for columns.

Removing a vectorize integration for a column does not change the column type or remove the vector embeddings stored in the column.

Returns a promise that resolves to a Table<NewSchema> instance that represents the table after the schema change.

Although the Table instance that you used to perform the alteration will still work, it will not reflect the updated typing if you added or dropped columns.

Adds or drops columns, or adds or removes a vectorize integration for columns.

Removing a vectorize integration for a column does not change the column type or remove the vector embeddings stored in the column.

Returns a Table<T> instance that represents the table after the schema change.

Although the Table instance that you used to perform the alteration will still work, it will not reflect the updated typing if you added or dropped columns.

Adds or drops columns, or adds or removes a vectorize integration for columns.

Removing a vectorize integration for a column does not change the column type or remove the vector embeddings stored in the column.

If the command succeeds, the response indicates the success.

Example response:

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

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

operation

AlterTableOperation | dict[str, Any]

The alter operation to perform.

Can be one of the following:

  • An AlterTableAddColumns object that specifies the columns to add

  • A dictionary in the form {"add": {"columns": …​}} that specifies the columns to add

  • An AlterTableDropColumns object that specifies the names of the columns to remove

  • A dictionary in the form {"drop": {"columns": …​}} that specifies the names of the columns to remove

  • An AlterTableAddVectorize object that specifies vectorize options and the names of the vector columns for which to add a vectorize integration

  • A dictionary in the form {"addVectorize": {"columns": …​}} that specifies vectorize options and the names of the vector columns for which to add a vectorize integration

  • An AlterTableDropVectorize object that specifies the names of the vector columns from which to remove a vectorize integration

  • A dictionary in the form {"dropVectorize": {"columns": …​}} that specifies the names of the vector columns from which to remove a vectorize integration

row_type

type

This parameter acts a formal specifier for the type checker. If omitted, the resulting Table is implicitly a Table[dict[str, Any]]. If provided, it must match the type hint specified in the assignment. For more information, see Typing support.

table_admin_timeout_ms

int

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

operation

AlterTableOperations<Schema>

The alter operation to perform.

Can be one of the following:

  • An {add: AddColumnOperation} object that specifies the columns to add

  • A {drop: DropColumnOperation} object that specifies the names of the columns to remove

  • An {addVectorize: AddVectorizeOperation} object that specifies vectorize options and the names of the vector columns for which to add a vectorize integration

  • A {dropVectorize: DropVectorizeOperation} object that specifies the names of the vector columns from which to remove a vectorize integration

timeout?

number | TimeoutDescriptor

The client-side timeout for this operation.

Options (AddColumnOperation):

Name Type Summary

columns

CreateTableColumnDefinitions

The column names, data types, and other settings (if required) for the new columns.

Column are defined in the same way as they are in createTable.

Options (DropColumnOperation):

Name Type Summary

columns

Cols<Schema>[]

The names of the columns to drop from the table.

Options (AddVectorizeOperation):

Name Type Summary

columns

Record<Cols<Schema>, VectorizeServiceOptions>

Specify the names of the vector columns to alter and the vectorize options for each column. The definition is the same as when you define columns in createTable. For more information, see Define a column to automatically generate vector embeddings.

Options (DropVectorizeOperation):

Name Type Summary

columns

Cols<Schema>[]

The names of the columns from which to remove vectorize information.

Name Type Summary

operation

AlterTableOperation

The alter operation to perform.

Can be one of the following:

options

AlterTableOptions

Specialization of the operation, including timeout.

rowClass

Class<?>

An optional new type for the row object. If not provided, the default is Row, which is like a Map object.

Name Type Summary

alterTable

command

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

operation

object

The alter operation to perform.

Can be one of the following:

  • An object in the form {add: {columns: COLUMN_DEFINITIONS}} that specifies the columns to add

  • An object in the form {drop: {columns: COLUMN_NAMES}} that specifies the names of the columns to remove

  • An object in the form {addVectorize: {columns: VECTORIZE_DEFINITIONS}} that specifies vectorize options and the names of the vector columns for which to add a vectorize integration

  • An object in the form {dropVectorize: {columns: COLUMN_NAMES}} object that specifies the names of the vector columns from which to remove a vectorize integration

operation.add.columns

object

Define columns to add to the table.

The format is the same as when you define columns in createTable.

operation.drop.columns

array

The names of the columns to remove from the table.

operation.addVectorize.columns

object

Provide the name of the target vector column, the dimension, and the vectorize service options.

service is an object containing provider, modelName, and other parameters for the embedding provider integration. Most integrations require authentication in service.authentication.providerKey or through an x-embedding-api-key header. For more information, see Vector type.

operation.dropVectorize.columns

array

The name of the vector column from which you want to remove the embedding provider integration.

Examples

The following examples demonstrate how to alter a table.

Add columns

When you add columns, the columns are defined in the same way as they are when you create a table.

  • Python

  • TypeScript

  • Java

  • curl

Add a column to a table:

my_table.alter(
    AlterTableAddColumns(
        columns={
            "tie_break": TableScalarColumnTypeDescriptor(
                column_type=ColumnType.BOOLEAN,
            ),
        },
    ),
)

Add columns to a table, and use the return value for strict control over types:

new_table: Table[MyCustomDictType] = my_table.alter(
    AlterTableAddColumns(
        columns={
            "tie_break": TableScalarColumnTypeDescriptor(
                column_type=ColumnType.BOOLEAN,
            ),
            "venue": TableScalarColumnTypeDescriptor(
                column_type=ColumnType.TEXT,
            ),
        },
    ),
    row_type=MyCustomDictType,
)

Example:

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 (
    AlterTableAddColumns,
    ColumnType,
    TableScalarColumnTypeDescriptor,
)

# Add a column
new_table = my_table.alter(
    AlterTableAddColumns(
        columns={
            "tie_break": TableScalarColumnTypeDescriptor(
                column_type=ColumnType.BOOLEAN,
            ),
        },
    ),
)

Add columns to the table, and update the Table type:

const newTable = await table.alter<NewSchema>({
  operation: {
    add: {
      columns: {
        tieBreak: 'boolean',
        venue: 'text',
      },
    },
  },
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTablePrimaryKey, InferTableSchema } 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;

// Infer the table type from the table definition.
// For information about table typing, see the documentation for create table.
type TableSchema = InferTableSchema<typeof TableDefinition>;

// The following script demonstrates all alter operations: add, drop, addVectorize, dropVectorize.
// This example also inserts rows to demonstrate the goal and outcome of each alter operation.
// You can only run one alter operation at a time, but you can have multiple operations in the same script.
(async function () {
  // Create a table or error if a 'games' table already exists.
  const table = await db.createTable<TableSchema>('games', { definition: TableDefinition });

  // Represents the new schema of the table after the alter to add columns
  type NewSchema = TableSchema & {
    tieBreak: boolean;
    venue: string;
  }

  // @ts-expect-error
  // Try to insert data into nonexistent columns.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  // Columns are defined in the same way that you define them in createTable, including name, type, and other properties.
  const altered = await table.alter<NewSchema>({
    operation: {
      add: {
        columns: {
          tieBreak: 'boolean',
          venue: 'text',
        },
      },
    },
  });

  // Attempt to insert the rows again.
  // This should succeed now that all columns exist in the table.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' });
  console.log('inserted', inserted.insertedId);

  // Represents the new schema of the table after the alter to drop columns
  type NewSchema = Omit<TableSchema, 'tieBreak' | 'venue'>

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  const altered = await table.alter<NewSchema>({
    operation: {
      drop: {
        columns: ['tieBreak', 'venue'],
      },
    },
  });

  // @ts-expect-error
  // Try to insert data into the removed columns.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // @ts-expect-error
  // Try to use vectorize on a vector column that doesn't have a vectorize integration.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Add the OpenAI embedding provider integration to the vector column.
  const altered = await table.alter({
    operation: {
      addVectorize: {
        columns: {
          mVector: {
            provider: 'openai',
            modelName: 'text-embedding-3-small',
            authentication: {
              providerKey: 'ASTRA_KMS_API_KEY_NAME',
            },
          },
        },
      },
    },
  });

  // Attempt to insert the row again.
  // This should succeed now that the vector column has a vectorize integration.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' });
  console.log('inserted', inserted.insertedId);

  // Remove vectorize from the specified vector column
  const altered = await table.alter({
    operation: {
      dropVectorize: {
        columns: ['mVector'],
      },
    },
  });

  // @ts-expect-error
  // Try to use vectorize on the vector column that no longer has a vectorize integration.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();

Expand the preceding Full script example for the definition of NewSchema that is used in the following truncated example:

// @ts-expect-error
// Try to insert data into nonexistent columns.
// This should error both statically and at runtime.
await table.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
  .catch(e => console.error(e.message));

// Provide the new type of the table as it would be after the alter.
// Note that this just returns the same Table object, but re-casted as the proper type.
// Columns are defined in the same way that you define them in createTable, including name, type, and other properties.
const altered = await table.alter<NewSchema>({
  operation: {
    add: {
      columns: {
        tieBreak: 'boolean',
        venue: 'text',
      },
    },
  },
});

// Attempt to insert the rows again.
// This should succeed now that all columns exist in the table.
const inserted = await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' });
console.log('inserted', inserted.insertedId);

Add a column to a table:

AlterTableAddColumns alterOperation = new AlterTableAddColumns()
  .addColumnBoolean("tie_break");
Table<Game> tableRow = myTable.alter(alterOperation);

Add columns to a table, providing a new row type, and specialize some options:

AlterTableAddColumns alterOperation = new AlterTableAddColumns()
  .addColumnBoolean("tie_break")
  .addColumnText("venue");
AlterTableOptions  alterOptions = new AlterTableOptions()
  .timeout(10000L);
// Notice the type hint for the new table
Table<EnhanceGame> myUpdatedTable = myTable
  .alter(alterOperation, alterOptions, EnhanceGame.class);

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.AlterTableAddColumns;
import com.datastax.astra.client.tables.definition.rows.Row;

public class AlterTableAddColumn {

 public static void main(String[] args) {
  // Database db = new DataAPIClient(token).getDatabase(endpoint);
  Database db = DataAPIClients.localDbWithDefaultKeyspace();
  Table<Row> myTable1 = db.getTable("games");

  // Add A Columns
  AlterTableAddColumns add = new AlterTableAddColumns()
          .addColumnBoolean("tie_break")
          .addColumnText("venue");
  myTable1.alter(add);

 }

}

Add a new column:

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 '{
  "alterTable": {
    "operation": {
      "add": {
        "columns": {
          "NEW_COLUMN_NAME": "DATA_TYPE"
        }
      }
    }
  }
}' | jq

Example:

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 '{
  "alterTable": {
    "operation": {
      "add": {
        "columns": {
          "deans_list": "boolean"
        }
      }
    }
  }
}' | jq

Drop columns

  • Python

  • TypeScript

  • Java

  • curl

Drop a column from a table:

new_table = my_table.alter(AlterTableDropColumns(
    columns=["tie_break"],
))

Drop columns from a table and use the return value for strict control over types:

new_table: Table[MyCustomNarrowDictType] = my_table.alter(
    AlterTableDropColumns(
        columns=["tie_break", "venue"],
    ),
    row_type=MyCustomNarrowDictType,
)

Example:

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 (
    AlterTableAddColumns,
    ColumnType,
    TableScalarColumnTypeDescriptor,
)

# Add a column
new_table = my_table.alter(
    AlterTableAddColumns(
        columns={
            "tie_break": TableScalarColumnTypeDescriptor(
                column_type=ColumnType.BOOLEAN,
            ),
        },
    ),
)

# Drop a column
from astrapy.info import AlterTableDropColumns

new_table = my_table.alter(AlterTableDropColumns(
    columns=["tie_break"],
))

Drop columns from the table and update the Table type:

const newTable = await table.alter<NewSchema>({
  operation: {
    drop: {
      columns: ['tieBreak', 'venue'],
    },
  },
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTablePrimaryKey, InferTableSchema } 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;

// Infer the table type from the table definition.
// For information about table typing, see the documentation for create table.
type TableSchema = InferTableSchema<typeof TableDefinition>;

// The following script demonstrates all alter operations: add, drop, addVectorize, dropVectorize.
// This example also inserts rows to demonstrate the goal and outcome of each alter operation.
// You can only run one alter operation at a time, but you can have multiple operations in the same script.
(async function () {
  // Create a table or error if a 'games' table already exists.
  const table = await db.createTable<TableSchema>('games', { definition: TableDefinition });

  // Represents the new schema of the table after the alter to add columns
  type NewSchema = TableSchema & {
    tieBreak: boolean;
    venue: string;
  }

  // @ts-expect-error
  // Try to insert data into nonexistent columns.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  // Columns are defined in the same way that you define them in createTable, including name, type, and other properties.
  const altered = await table.alter<NewSchema>({
    operation: {
      add: {
        columns: {
          tieBreak: 'boolean',
          venue: 'text',
        },
      },
    },
  });

  // Attempt to insert the rows again.
  // This should succeed now that all columns exist in the table.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' });
  console.log('inserted', inserted.insertedId);

  // Represents the new schema of the table after the alter to drop columns
  type NewSchema = Omit<TableSchema, 'tieBreak' | 'venue'>

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  const altered = await table.alter<NewSchema>({
    operation: {
      drop: {
        columns: ['tieBreak', 'venue'],
      },
    },
  });

  // @ts-expect-error
  // Try to insert data into the removed columns.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // @ts-expect-error
  // Try to use vectorize on a vector column that doesn't have a vectorize integration.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Add the OpenAI embedding provider integration to the vector column.
  const altered = await table.alter({
    operation: {
      addVectorize: {
        columns: {
          mVector: {
            provider: 'openai',
            modelName: 'text-embedding-3-small',
            authentication: {
              providerKey: 'ASTRA_KMS_API_KEY_NAME',
            },
          },
        },
      },
    },
  });

  // Attempt to insert the row again.
  // This should succeed now that the vector column has a vectorize integration.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' });
  console.log('inserted', inserted.insertedId);

  // Remove vectorize from the specified vector column
  const altered = await table.alter({
    operation: {
      dropVectorize: {
        columns: ['mVector'],
      },
    },
  });

  // @ts-expect-error
  // Try to use vectorize on the vector column that no longer has a vectorize integration.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();

Expand the preceding Full script example for the definition of NewSchema that is used in the following truncated example:

// Provide the new type of the table as it would be after the alter.
// Note that this just returns the same Table object, but re-casted as the proper type.
const altered = await table.alter<NewSchema>({
  operation: {
    drop: {
      columns: ['tieBreak', 'venue'],
    },
  },
});

// @ts-expect-error
// Try to insert data into the removed columns.
// This should error both statically and at runtime.
await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
  .catch(e => console.error(e.message));

Drop a column from a table:

myTable.alter(new AlterTableDropColumns("tie_break"));

Drop columns from a table, use the return value for strict control over types, and specialize with options:

AlterTableDropColumns alterOperation = new AlterTableDropColumns()
 .columns("tie_break", "venue");
AlterTableOptions  alterOptions = new AlterTableOptions()
 .timeout(10000L);
Table<Game> myUpdatedTable = myTable
  .alter(alterOperation, alterOptions, Game.class);

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.AlterTableAddColumns;
import com.datastax.astra.client.tables.commands.AlterTableDropColumns;
import com.datastax.astra.client.tables.definition.rows.Row;

public class AlterTableDropColumn {

 public static void main(String[] args) {
  // Database db = new DataAPIClient(token).getDatabase(endpoint);
  Database db = DataAPIClients.localDbWithDefaultKeyspace();
  Table<Row> myTable1 = db.getTable("games");

  // Add A Columns
  AlterTableDropColumns dropColumn = new AlterTableDropColumns("tie_break");
  myTable1.alter(dropColumn);

 }

}

Drop a column:

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 '{
  "alterTable": {
    "operation": {
      "drop": {
        "columns": [ "COLUMN_NAME", "COLUMN_NAME" ]
      }
    }
  }
}' | jq

Example:

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 '{
  "alterTable": {
    "operation": {
      "drop": {
        "columns": [ "deans_list" ]
      }
    }
  }
}' | jq

Add automatic embedding generation for vector columns

To automatically generate embeddings with vectorize, you configure an embedding provider integration on a vector column. Astra DB stores the automatically-generated embeddings in this column.

For information about inserting vector data and automatically generating embeddings in tables, see Vector type, Insert a row, and Insert rows.

  • Python

  • TypeScript

  • Java

  • curl

Add vectorize to a column:

my_table.alter(
    AlterTableAddVectorize(
        columns={
            "m_vector": VectorServiceOptions(
                provider="openai",
                model_name="text-embedding-3-small",
                authentication={
                    "providerKey": "ASTRA_KMS_API_KEY_NAME",
                },
            ),
        },
    ),
)

Example:

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 AlterTableAddVectorize, VectorServiceOptions

new_table = my_table.alter(
    AlterTableAddVectorize(
        columns={
            "m_vector": VectorServiceOptions(
                provider="openai",
                model_name="text-embedding-3-small",
                authentication={
                    "providerKey": "ASTRA_KMS_API_KEY_NAME",
                },
            ),
        },
    ),
)

Add vectorize to a column:

const newTable = await table.alter({
  operation: {
    addVectorize: {
      columns: {
        mVector: {
          provider: 'openai',
          modelName: 'text-embedding-3-small',
          authentication: {
            providerKey: 'ASTRA_KMS_API_KEY_NAME',
          },
        },
      },
    },
  },
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTablePrimaryKey, InferTableSchema } 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;

// Infer the table type from the table definition.
// For information about table typing, see the documentation for create table.
type TableSchema = InferTableSchema<typeof TableDefinition>;

// The following script demonstrates all alter operations: add, drop, addVectorize, dropVectorize.
// This example also inserts rows to demonstrate the goal and outcome of each alter operation.
// You can only run one alter operation at a time, but you can have multiple operations in the same script.
(async function () {
  // Create a table or error if a 'games' table already exists.
  const table = await db.createTable<TableSchema>('games', { definition: TableDefinition });

  // Represents the new schema of the table after the alter to add columns
  type NewSchema = TableSchema & {
    tieBreak: boolean;
    venue: string;
  }

  // @ts-expect-error
  // Try to insert data into nonexistent columns.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  // Columns are defined in the same way that you define them in createTable, including name, type, and other properties.
  const altered = await table.alter<NewSchema>({
    operation: {
      add: {
        columns: {
          tieBreak: 'boolean',
          venue: 'text',
        },
      },
    },
  });

  // Attempt to insert the rows again.
  // This should succeed now that all columns exist in the table.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' });
  console.log('inserted', inserted.insertedId);

  // Represents the new schema of the table after the alter to drop columns
  type NewSchema = Omit<TableSchema, 'tieBreak' | 'venue'>

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  const altered = await table.alter<NewSchema>({
    operation: {
      drop: {
        columns: ['tieBreak', 'venue'],
      },
    },
  });

  // @ts-expect-error
  // Try to insert data into the removed columns.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // @ts-expect-error
  // Try to use vectorize on a vector column that doesn't have a vectorize integration.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Add the OpenAI embedding provider integration to the vector column.
  const altered = await table.alter({
    operation: {
      addVectorize: {
        columns: {
          mVector: {
            provider: 'openai',
            modelName: 'text-embedding-3-small',
            authentication: {
              providerKey: 'ASTRA_KMS_API_KEY_NAME',
            },
          },
        },
      },
    },
  });

  // Attempt to insert the row again.
  // This should succeed now that the vector column has a vectorize integration.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' });
  console.log('inserted', inserted.insertedId);

  // Remove vectorize from the specified vector column
  const altered = await table.alter({
    operation: {
      dropVectorize: {
        columns: ['mVector'],
      },
    },
  });

  // @ts-expect-error
  // Try to use vectorize on the vector column that no longer has a vectorize integration.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();
// @ts-expect-error
// Try to use vectorize on a vector column that doesn't have a vectorize integration.
// This should error both statically and at runtime.
await table.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
  .catch(e => console.error(e.message));

// Add the OpenAI embedding provider integration to the vector column.
const altered = await table.alter({
  operation: {
    addVectorize: {
      columns: {
        mVector: {
          provider: 'openai',
          modelName: 'text-embedding-3-small',
          authentication: {
            providerKey: 'ASTRA_KMS_API_KEY_NAME',
          },
        },
      },
    },
  },
});

// Attempt to insert the row again.
// This should succeed now that the vector column has a vectorize integration.
const inserted = await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' });
console.log('inserted', inserted.insertedId);

Add vectorize to a column:

VectorServiceOptions options = new VectorServiceOptions()
   .modelName("text-embedding-3-small")
   .provider("openai")
   .authentication(Map.of("providerKey", "ASTRA_KMS_API_KEY_NAME"));
AlterTableAddVectorize addVectorize =
 new AlterTableAddVectorize()
  .columns(Map.of("m_vector", options));

myTable1.alter(addVectorize);

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.vectorize.VectorServiceOptions;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.AlterTableAddVectorize;
import com.datastax.astra.client.tables.definition.rows.Row;

import java.util.Map;

public class AlterTableAddVectorizes {

 public static void main(String[] args) {
  // Database db = new DataAPIClient(token).getDatabase(endpoint);
  Database db = DataAPIClients.localDbWithDefaultKeyspace();
  Table<Row> myTable1 = db.getTable("games");
  AlterTableAddVectorize addVectorize =
   new AlterTableAddVectorize().columns(
    Map.of("m_vector", new VectorServiceOptions()
     .modelName("text-embedding-3-small")
     .provider("openai").authentication(
      Map.of("providerKey", "ASTRA_KMS_API_KEY_NAME")
   ))
  );
  myTable1.alter(addVectorize);
 }

}

Add a vectorize embedding provider integration to an existing vector column:

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 '{
  "alterTable": {
    "operation": {
      "addVectorize": {
        "columns": {
          "VECTOR_COLUMN_NAME": {
            "type": "vector",
            "dimension": NUM_DIMENSIONS,
            "service": {
              "provider": "EMBEDDINGS_PROVIDER_NAME",
              "modelName": "MODEL_NAME"
            }
          }
        }
      }
    }
  }
}' | jq

Example:

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 '{
  "alterTable": {
    "operation": {
      "addVectorize": {
        "columns": {
          "embedding": {
            "type": "vector",
            "dimension": 1024,
            "service": {
              "provider": "mistral",
              "modelName": "mistral-embed",
              "authentication": {
                "providerKey": "mistral-api-key"
              }
            }
          }
        }
      }
    }
  }
}' | jq

Remove automatic embedding generation for vector columns

You can remove automatic embedding generation for one or more vector columns.

  • Python

  • TypeScript

  • Java

  • curl

Remove vectorize from a column:

new_table = my_table.alter(
    AlterTableDropVectorize(columns=["m_vector"]),
)

Example:

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 AlterTableAddVectorize, VectorServiceOptions

new_table = my_table.alter(
    AlterTableAddVectorize(
        columns={
            "m_vector": VectorServiceOptions(
                provider="openai",
                model_name="text-embedding-3-small",
                authentication={
                    "providerKey": "ASTRA_KMS_API_KEY_NAME",
                },
            ),
        },
    ),
)

from astrapy.info import AlterTableDropVectorize

# Drop vectorize from a (vector) column
new_table = my_table.alter(
    AlterTableDropVectorize(columns=["m_vector"]),
)

Remove vectorize from a table column:

const newTable = await table.alter({
  operation: {
    dropVectorize: {
      columns: ['mVector'],
    },
  },
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTablePrimaryKey, InferTableSchema } 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;

// Infer the table type from the table definition.
// For information about table typing, see the documentation for create table.
type TableSchema = InferTableSchema<typeof TableDefinition>;

// The following script demonstrates all alter operations: add, drop, addVectorize, dropVectorize.
// This example also inserts rows to demonstrate the goal and outcome of each alter operation.
// You can only run one alter operation at a time, but you can have multiple operations in the same script.
(async function () {
  // Create a table or error if a 'games' table already exists.
  const table = await db.createTable<TableSchema>('games', { definition: TableDefinition });

  // Represents the new schema of the table after the alter to add columns
  type NewSchema = TableSchema & {
    tieBreak: boolean;
    venue: string;
  }

  // @ts-expect-error
  // Try to insert data into nonexistent columns.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  // Columns are defined in the same way that you define them in createTable, including name, type, and other properties.
  const altered = await table.alter<NewSchema>({
    operation: {
      add: {
        columns: {
          tieBreak: 'boolean',
          venue: 'text',
        },
      },
    },
  });

  // Attempt to insert the rows again.
  // This should succeed now that all columns exist in the table.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' });
  console.log('inserted', inserted.insertedId);

  // Represents the new schema of the table after the alter to drop columns
  type NewSchema = Omit<TableSchema, 'tieBreak' | 'venue'>

  // Provide the new type of the table as it would be after the alter.
  // Note that this just returns the same Table object, but re-casted as the proper type.
  const altered = await table.alter<NewSchema>({
    operation: {
      drop: {
        columns: ['tieBreak', 'venue'],
      },
    },
  });

  // @ts-expect-error
  // Try to insert data into the removed columns.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, tieBreak: true, venue: 'Thunderdome' })
    .catch(e => console.error(e.message));

  // @ts-expect-error
  // Try to use vectorize on a vector column that doesn't have a vectorize integration.
  // This should error both statically and at runtime.
  await table.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Add the OpenAI embedding provider integration to the vector column.
  const altered = await table.alter({
    operation: {
      addVectorize: {
        columns: {
          mVector: {
            provider: 'openai',
            modelName: 'text-embedding-3-small',
            authentication: {
              providerKey: 'ASTRA_KMS_API_KEY_NAME',
            },
          },
        },
      },
    },
  });

  // Attempt to insert the row again.
  // This should succeed now that the vector column has a vectorize integration.
  const inserted = await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' });
  console.log('inserted', inserted.insertedId);

  // Remove vectorize from the specified vector column
  const altered = await table.alter({
    operation: {
      dropVectorize: {
        columns: ['mVector'],
      },
    },
  });

  // @ts-expect-error
  // Try to use vectorize on the vector column that no longer has a vectorize integration.
  // This should error both statically and at runtime.
  await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
    .catch(e => console.error(e.message));

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();
// Remove vectorize from the specified vector column
const altered = await table.alter({
  operation: {
    dropVectorize: {
      columns: ['mVector'],
    },
  },
});

// @ts-expect-error
// Try to use vectorize on the vector column that no longer has a vectorize integration.
// This should error both statically and at runtime.
await altered.insertOne({ matchId: '1', round: 1, mVector: 'The ☀️, The 🌙, The 🌟' })
  .catch(e => console.error(e.message));

Remove vectorize from a column:

AlterTableDropVectorize dropVectorize =
  new AlterTableDropVectorize("m_vector");
myTable1.alter(dropVectorize);

Example:

package com.datastax.astra.client.database;

import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.commands.AlterTableDropColumns;
import com.datastax.astra.client.tables.commands.AlterTableDropVectorize;
import com.datastax.astra.client.tables.definition.rows.Row;

public class AlterTableDropVectorizes {

 public static void main(String[] args) {
  // Database db = new DataAPIClient(token).getDatabase(endpoint);
  Database db = DataAPIClients.localDbWithDefaultKeyspace();
  Table<Row> myTable1 = db.getTable("games");

  // Add A Columns
  AlterTableDropVectorize dropVectorize = new AlterTableDropVectorize("m_vector");
  myTable1.alter(dropVectorize);

 }

}

Remove an embedding provider integration from a vector column:

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 '{
  "alterTable": {
    "operation": {
      "dropVectorize": {
        "columns": [ "VECTOR_COLUMN_NAME" ]
      }
    }
  }
}' | jq

Example:

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 '{
  "alterTable": {
    "operation": {
      "dropVectorize": {
        "columns": [ "embedding" ]
      }
    }
  }
}' | jq

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