Create a table
Creates a new table in a keyspace in a database.
After you create a table, index columns that you want to sort or filter. This optimizes your queries and avoids resource intensive, long running allow filtering operations. All indexed column names must use snake case, not camel case.
You can also modify the table columns later. To add data to your table, insert rows.
|
Ready to write code? See the examples for this method to get started. If you are new to the Data API, check out the quickstart. |
Result
-
Python
-
TypeScript
-
Java
-
C#
-
curl
Creates a table with the specified parameters.
Returns a Table object.
You can use this object to work with rows in the table.
Unless you specify the row_type parameter, the table is typed as Table[dict].
For more information, see Typing support.
Creates a table with the specified parameters.
Returns a promise that resolves to a <Table<Schema, PKey>> object.
You can use this object to work with rows in the table.
Unless you specify the Schema, the table is typed as Table<Record<string, any>>.
Creates a table with the specified parameters.
Returns a Table<T> object.
You can use this object to work with rows in the table.
Unless you specify the rowClass parameter, the table is typed as Table<Row>.
Creates a table with the specified parameters.
Returns a Table object.
You can use this object to work with rows in the table.
By default, the Table object is typed as Table<Row>, where Row is Dictionary<string, object>.
You can enable stronger typing by specifying a type when you create the table.
For more information and examples, see Custom typing for tables.
Creates a table with the specified parameters.
If the command succeeds, the response indicates the success.
Example successful response:
{
"status": {
"ok": 1
}
}
Parameters
-
Python
-
TypeScript
-
Java
-
C#
-
curl
Use the create_table method, which belongs to the astrapy.Database class.
Method signature
create_table(
name: str,
*,
definition: CreateTableDefinition | dict[str, Any],
row_type: type[Any],
keyspace: str,
if_not_exists: bool,
table_admin_timeout_ms: int,
request_timeout_ms: int,
timeout_ms: int,
spawn_api_options: APIOptions,
) -> Table[ROW]
| Name | Type | Summary |
|---|---|---|
|
|
The name of the table. Table names must follow these rules:
|
|
|
The full schema for the table, including column names, column data types, and the primary key. See the examples for usage. All column names used in the schema must be unique within the table. Any columns that will be indexes must use snake case, not camel case, for their name. |
|
|
Optional.
A formal specifier for the type checker.
If provided, Default: |
|
|
Optional if you specified a keyspace when instantiating the Default: The working keyspace for the database. |
|
|
Optional. Whether the command should silently succeed even if a table with the given name already exists in the keyspace and no new table was created. This option only checks table names. It does not check table schemas. Default: false |
|
Optional.
A complete or partial specification of the APIOptions to override the defaults inherited from the If |
|
|
|
Optional.
A timeout, in milliseconds, for the underlying HTTP request.
If not provided, the |
Use the createTable method, which belongs to the Db class.
Method signature
async createTable<const Def extends CreateTableDefinition>(
name: string,
options: {
definition: CreateTableDefinition,
ifNotExists?: boolean,
logging?: DataAPILoggingConfig,
serdes?: TableSerDesConfig,
timeoutDefaults?: Partial<TimeoutDescriptor>,
keyspace?: string,
}
): Table<InferTableSchema<Def>, InferTablePrimaryKey<Def>>
Parameters:
| Name | Type | Summary |
|---|---|---|
|
|
The name of the table. Table names must follow these rules:
|
|
|
The options for this operation. See Properties of |
| Name | Type | Summary |
|---|---|---|
|
|
The full schema for the table, including column names, column data types, and the primary key. See the examples for usage. All column names used in the schema must be unique within the table. Any columns that will be indexes must use snake case, not camel case, for their name. |
|
|
Optional. Whether the command should silently succeed even if a table with the given name already exists in the keyspace and no new table was created. This option only checks table names. It does not check table schemas. Default: false |
|
|
Optional if you specified a keyspace when instantiating the Default: The working keyspace for the database. |
|
|
Optional.
The configuration for logging events emitted by the |
|
|
Optional.
The default timeout options for any operation performed on this |
|
|
Optional. Lower-level serialization/deserialization configuration for this table. For more information, see Custom Ser/Des. |
Use the createTable method, which belongs to the com.datastax.astra.client.databases.Database class.
Method signature
<T> Table<T> createTable(
String tableName,
TableDefinition tableDefinition,
Class<T> rowClass,
CreateTableOptions createTableOptions
)
<T> Table<T> createTable(
String tableName,
TableDefinition tableDefinition,
Class<T> rowClass
)
<T> Table<T> createTable(Class<T> rowClass)
<T> Table<T> createTable(
Class<T> rowClass,
CreateTableOptions createTableOptions
)
<T> Table<T> createTable(
String tableName,
Class<T> rowClass,
CreateTableOptions createTableOptions
)
Table<Row> createTable(
String tableName,
TableDefinition tableDefinition,
CreateTableOptions options
)
Table<Row> createTable(
String tableName,
TableDefinition tableDefinition
)
| Name | Type | Summary |
|---|---|---|
|
|
The name of the table. Table names must follow these rules:
|
|
The full schema for the table, including column names, column data types, and the primary key. See the examples for usage. All column names used in the schema must be unique within the table. Any columns that will be indexes must use snake case, not camel case, for their name. |
|
|
|
Optional. A specification of the class of the table’s row object. Default: |
|
Optional.
The options for this operation. See Selected methods of |
| Method | Parameters | Summary |
|---|---|---|
|
|
Optional. Whether the command should silently succeed even if a table with the given name already exists in the keyspace and no new table was created. This option only checks table names. It does not check table schemas. Default: false |
|
|
Optional.
A timeout, in milliseconds, for the underlying HTTP request.
If not provided, the |
Use the CreateTableAsync method, which belongs to the Database class.
You can also use CreateTable, which is the synchronous version of the method.
Method signature
public Task<Table<TRow>> CreateTableAsync<TRow>(
TableDefinition definition, CreateTableOptions options = null
) where TRow : class, new();
public Task<Table<TRow>> CreateTableAsync<TRow>(
string tableName,
TableDefinition definition,
CreateTableOptions options = null
) where TRow : class;
public Task<Table<TRow>> CreateTableAsync<TRow>(
string tableName, CreateTableOptions options = null
) where TRow : class, new();
public Task<Table<Row>> CreateTableAsync(
string tableName,
TableDefinition definition,
CreateTableOptions options = null
);
public Task<Table<TRow>> CreateTableAsync<TRow>(
CreateTableOptions options = null
) where TRow : class, new();
| Name | Type | Summary |
|---|---|---|
|
|
The name of the table. Table names must follow these rules:
If not specified, the client attempts to extract it from the |
|
The full schema for the table, including column names, column data types, and the primary key. See the examples for usage. All column names used in the schema must be unique within the table. Any columns that will be indexes must use snake case, not camel case, for their name. |
|
|
Optional.
Options for this operation.
Keyspace is required unless you specified a keyspace when instantiating the |
Use the createTable command.
Command signature
curl -sS -L -X POST "API_ENDPOINT/api/json/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "TABLE_NAME",
"definition": {
"columns": {
"COLUMN_NAME": "DATA_TYPE",
"COLUMN_NAME": "DATA_TYPE"
},
"primaryKey": "PRIMARY_KEY_DEFINITION"
}
}
}'
| Name | Type | Summary |
|---|---|---|
|
|
The name of the table. Table names must follow these rules:
|
|
|
The full schema for the table, including column names, column data types, and the primary key. See the examples for usage.
See Properties of |
| Name | Type | Summary |
|---|---|---|
|
|
The column names and data types. All column names must be unique within the table. Any columns that will be indexes must use snake case, not camel case, for their name. See the examples for usage. |
|
|
The primary key for the table. See the examples for usage. |
Examples
The following examples demonstrate how to create a table.
Create a table with a single-column primary key
A single-column primary key is a primary key consisting of one column. For more information, see Primary keys in tables.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The Python client supports multiple ways to create a table.
In all cases, you must define the table schema, and then pass the definition to the create_table method.
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
-
CreateTableDefinition object
-
Fluent interface
-
Dictionary
You can define the table as a CreateTableDefinition and then build the table from the CreateTableDefinition object.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TableKeyValuedColumnType,
TableKeyValuedColumnTypeDescriptor,
TablePrimaryKeyDescriptor,
TableScalarColumnTypeDescriptor,
TableValuedColumnType,
TableValuedColumnTypeDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = CreateTableDefinition(
# Define all of the columns in the table
columns={
"title": TableScalarColumnTypeDescriptor(
column_type=ColumnType.TEXT
),
"number_of_pages": TableScalarColumnTypeDescriptor(
column_type=ColumnType.INT
),
"rating": TableScalarColumnTypeDescriptor(
column_type=ColumnType.FLOAT
),
"genres": TableValuedColumnTypeDescriptor(
column_type=TableValuedColumnType.SET,
value_type=ColumnType.TEXT,
),
"metadata": TableKeyValuedColumnTypeDescriptor(
column_type=TableKeyValuedColumnType.MAP,
key_type=ColumnType.TEXT,
value_type=ColumnType.TEXT,
),
"is_checked_out": TableScalarColumnTypeDescriptor(
column_type=ColumnType.BOOLEAN
),
"due_date": TableScalarColumnTypeDescriptor(
column_type=ColumnType.DATE
),
},
# Define the primary key for the table.
# In this case, the table uses a single-column primary key.
primary_key=TablePrimaryKeyDescriptor(
partition_by=["title"], partition_sort={}
),
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can use a fluent interface to build the table definition and then create the table from the definition.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import ColumnType, CreateTableDefinition
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = (
CreateTableDefinition.builder()
# Define all of the columns in the table
.add_column("title", ColumnType.TEXT)
.add_column("number_of_pages", ColumnType.INT)
.add_column("rating", ColumnType.FLOAT)
.add_set_column(
"genres",
ColumnType.TEXT,
)
.add_map_column(
"metadata",
# This is the key type for the map column
ColumnType.TEXT,
# This is the value type for the map column
ColumnType.TEXT,
)
.add_column("is_checked_out", ColumnType.BOOLEAN)
.add_column("due_date", ColumnType.DATE)
# Define the primary key for the table.
# In this case, the table uses a single-column primary key.
.add_partition_by(["title"])
# Finally, build the table definition.
.build()
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can define the table as a dictionary and then build the table from the dictionary.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
# Define the columns and primary key for the table
table_definition = {
"columns": {
"title": {"type": "text"},
"number_of_pages": {"type": "int"},
"rating": {"type": "float"},
"genres": {"type": "set", "valueType": "text"},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text",
},
"is_checked_out": {"type": "boolean"},
"due_date": {"type": "date"},
},
"primaryKey": {
"partitionBy": ["title"],
"partitionSort": {},
},
}
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
The TypeScript client supports multiple ways to create a table. The method you choose depends on your typing preferences and whether you modified the ser/des configuration.
For more information, see Collection and table typing.
-
Automatic type inference
-
Manually typed tables
-
Untyped tables
The TypeScript client can automatically infer the TypeScript-equivalent type of the table’s schema and primary key.
To do this, first create the table definition.
Then, use InferTableSchema and InferTablePrimaryKey to infer the type of the table and of the primary key.
To create the table, provide the table definition and the inferred types to the createTable method.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
InferTablePrimaryKey,
InferTableSchema,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["title"],
},
});
// Infer the TypeScript-equivalent type of the table's schema and primary key
type TableSchema = InferTableSchema<typeof tableDefinition>;
type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;
(async function () {
// Provide the types and the definition
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
You can manually define the type for your table’s schema and primary key.
To create the table, provide the table definition and the types to the createTable method.
This may be necessary if you modify the table’s default ser/des configuration.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIDate,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["title"],
},
});
// Manually define the type of the table's schema and primary key
type TableSchema = {
title: string;
number_of_pages?: number | null | undefined;
rating?: number | null | undefined;
genres?: Set<string> | undefined;
metadata?: Map<string, string> | undefined;
is_checked_out?: boolean | null | undefined;
due_date?: DataAPIDate | null | undefined;
};
type TablePrimaryKey = Pick<TableSchema, "title">;
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
To create a table without any typing, pass SomeRow as the single generic type parameter to the createTable method.
This types the table’s rows as Record<string, any>.
This is the most flexible but least type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
SomeRow,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["title"],
},
});
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<SomeRow>("example_table", {
definition: tableDefinition,
keyspace: "KEYSPACE_NAME",
});
})();
The Java client supports multiple ways to create a table. In all cases, you must define the table schema.
-
Use a generic type
-
Define the row type
If you don’t specify the Class parameter when creating an instance of the generic class Table, the client defaults Table as the type.
In this case, the working object type T is Row.class.
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.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.rows.Row;
public class Example {
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnText("title")
.addColumnInt("number_of_pages")
.addColumn("rating", TableColumnTypes.FLOAT)
.addColumnSet("genres", TableColumnTypes.TEXT)
.addColumnMap("metadata", TableColumnTypes.TEXT, TableColumnTypes.TEXT)
.addColumnBoolean("is_checked_out")
.addColumn("due_date", TableColumnTypes.DATE)
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
.addPartitionBy("title");
Table<Row> table = database.createTable("example_table", tableDefinition);
}
}
Instead of using the default type Row.class, you can define your own working object, which will be serialized as a Row.
This working object can be annotated when the field names do not exactly match the column names or when you want to fully describe your table to enable its creation solely from the entity definition.
The following example defines a Book class and then uses it to create the table.
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.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.mapping.Column;
import com.datastax.astra.client.tables.mapping.EntityTable;
import com.datastax.astra.client.tables.mapping.PartitionBy;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import lombok.Data;
public class Example {
@EntityTable("example_table")
@Data
public class Book {
@PartitionBy(0)
@Column(name = "title", type = TableColumnTypes.TEXT)
private String title;
@Column(name = "number_of_pages", type = TableColumnTypes.INT)
private Integer number_of_pages;
@Column(name = "rating", type = TableColumnTypes.FLOAT)
private Float rating;
@Column(name = "genres", type = TableColumnTypes.SET, valueType = TableColumnTypes.TEXT)
private Set<String> genres;
@Column(
name = "metadata",
type = TableColumnTypes.MAP,
keyType = TableColumnTypes.TEXT,
valueType = TableColumnTypes.TEXT)
private Map<String, String> metadata;
@Column(name = "is_checked_out", type = TableColumnTypes.BOOLEAN)
private Boolean is_checked_out;
@Column(name = "due_date", type = TableColumnTypes.DATE)
private Date due_date;
}
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Table<Book> table = database.createTable(Book.class);
}
}
-
Typed tables
-
Untyped tables
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
// Define the type for the row
[TableName("TABLE_NAME")]
public class Book
{
[ColumnPrimaryKey]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnName("rating")]
public float? Rating { get; set; }
[ColumnName("genres")]
public string[]? Genres { get; set; }
[ColumnName("metadata")]
public Dictionary<string, string>? Metadata { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
[ColumnName("due_date")]
public DateOnly? DueDate { get; set; }
}
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var table = await database.CreateTableAsync<Book>();
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
using DataStax.AstraDB.DataApi.Utils;
namespace Examples;
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var definition = new TableDefinition()
.AddColumn("title", DataAPIType.Text())
.AddColumn("number_of_pages", DataAPIType.Int())
.AddColumn("rating", DataAPIType.Float())
.AddColumn("genres", DataAPIType.Set(DataAPIType.Text()))
.AddColumn(
"metadata",
DataAPIType.Map(DataAPIType.Text(), DataAPIType.Text())
)
.AddColumn("is_checked_out", DataAPIType.Boolean())
.AddColumn("due_date", DataAPIType.Date())
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
.AddSinglePrimaryKey("title");
var table = await database.CreateTableAsync(
"TABLE_NAME",
definition
);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "example_table",
"definition": {
"columns": {
"title": {
"type": "text"
},
"number_of_pages": {
"type": "int"
},
"rating": {
"type": "float"
},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text"
},
"genres": {
"type": "set",
"valueType": "text"
},
"is_checked_out": {
"type": "boolean"
},
"due_date": {
"type": "date"
}
},
"primaryKey": "title"
}
}
}'
Create a table with a composite primary key
A composite primary key is a primary key consisting of multiple columns. For more information, see Primary keys in tables.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The Python client supports multiple ways to create a table.
In all cases, you must define the table schema, and then pass the definition to the create_table method.
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
-
CreateTableDefinition object
-
Fluent interface
-
Dictionary
You can define the table as a CreateTableDefinition and then build the table from the CreateTableDefinition object.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TableKeyValuedColumnType,
TableKeyValuedColumnTypeDescriptor,
TablePrimaryKeyDescriptor,
TableScalarColumnTypeDescriptor,
TableValuedColumnType,
TableValuedColumnTypeDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = CreateTableDefinition(
# Define all of the columns in the table
columns={
"title": TableScalarColumnTypeDescriptor(
column_type=ColumnType.TEXT
),
"number_of_pages": TableScalarColumnTypeDescriptor(
column_type=ColumnType.INT
),
"rating": TableScalarColumnTypeDescriptor(
column_type=ColumnType.FLOAT
),
"genres": TableValuedColumnTypeDescriptor(
column_type=TableValuedColumnType.SET,
value_type=ColumnType.TEXT,
),
"metadata": TableKeyValuedColumnTypeDescriptor(
column_type=TableKeyValuedColumnType.MAP,
key_type=ColumnType.TEXT,
value_type=ColumnType.TEXT,
),
"is_checked_out": TableScalarColumnTypeDescriptor(
column_type=ColumnType.BOOLEAN
),
"due_date": TableScalarColumnTypeDescriptor(
column_type=ColumnType.DATE
),
},
# Define the primary key for the table.
# In this case, the table uses a composite primary key.
primary_key=TablePrimaryKeyDescriptor(
partition_by=["title", "rating"], partition_sort={}
),
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can use a fluent interface to build the table definition and then create the table from the definition.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import ColumnType, CreateTableDefinition
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = (
CreateTableDefinition.builder()
# Define all of the columns in the table
.add_column("title", ColumnType.TEXT)
.add_column("number_of_pages", ColumnType.INT)
.add_column("rating", ColumnType.FLOAT)
.add_set_column(
"genres",
ColumnType.TEXT,
)
.add_map_column(
"metadata",
# This is the key type for the map column
ColumnType.TEXT,
# This is the value type for the map column
ColumnType.TEXT,
)
.add_column("is_checked_out", ColumnType.BOOLEAN)
.add_column("due_date", ColumnType.DATE)
# Define the primary key for the table.
# In this case, the table uses a composite primary key.
.add_partition_by(["title", "rating"])
# Finally, build the table definition.
.build()
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can define the table as a dictionary and then build the table from the dictionary.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
# Define the columns and primary key for the table
table_definition = {
"columns": {
"title": {"type": "text"},
"number_of_pages": {"type": "int"},
"rating": {"type": "float"},
"genres": {"type": "set", "valueType": "text"},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text",
},
"is_checked_out": {"type": "boolean"},
"due_date": {"type": "date"},
},
"primaryKey": {
"partitionBy": ["title", "rating"],
"partitionSort": {},
},
}
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
The TypeScript client supports multiple ways to create a table. The method you choose depends on your typing preferences and whether you modified the ser/des configuration.
For more information, see Collection and table typing.
-
Automatic type inference
-
Manually typed tables
-
Untyped tables
The TypeScript client can automatically infer the TypeScript-equivalent type of the table’s schema and primary key.
To do this, first create the table definition.
Then, use InferTableSchema and InferTablePrimaryKey to infer the type of the table and of the primary key.
To create the table, provide the table definition and the inferred types to the createTable method.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
InferTablePrimaryKey,
InferTableSchema,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
primaryKey: {
partitionBy: ["title", "rating"],
},
});
// Infer the TypeScript-equivalent type of the table's schema and primary key
type TableSchema = InferTableSchema<typeof tableDefinition>;
type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;
(async function () {
// Provide the types and the definition
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
You can manually define the type for your table’s schema and primary key.
To create the table, provide the table definition and the types to the createTable method.
This may be necessary if you modify the table’s default ser/des configuration.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIDate,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
primaryKey: {
partitionBy: ["title", "rating"],
},
});
// Manually define the type of the table's schema and primary key
type TableSchema = {
title: string;
number_of_pages?: number | null | undefined;
rating?: number | null | undefined;
genres?: Set<string> | undefined;
metadata?: Map<string, string> | undefined;
is_checked_out?: boolean | null | undefined;
due_date?: DataAPIDate | null | undefined;
};
type TablePrimaryKey = Pick<TableSchema, "title" | "rating">;
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
To create a table without any typing, pass SomeRow as the single generic type parameter to the createTable method.
This types the table’s rows as Record<string, any>.
This is the most flexible but least type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
SomeRow,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
primaryKey: {
partitionBy: ["title", "rating"],
},
});
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<SomeRow>("example_table", {
definition: tableDefinition,
keyspace: "KEYSPACE_NAME",
});
})();
The Java client supports multiple ways to create a table. In all cases, you must define the table schema.
-
Use a generic type
-
Define the row type
If you don’t specify the Class parameter when creating an instance of the generic class Table, the client defaults Table as the type.
In this case, the working object type T is Row.class.
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.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.rows.Row;
public class Example {
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnText("title")
.addColumnInt("number_of_pages")
.addColumn("rating", TableColumnTypes.FLOAT)
.addColumnSet("genres", TableColumnTypes.TEXT)
.addColumnMap("metadata", TableColumnTypes.TEXT, TableColumnTypes.TEXT)
.addColumnBoolean("is_checked_out")
.addColumn("due_date", TableColumnTypes.DATE)
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
.addPartitionBy("title")
.addPartitionBy("rating");
Table<Row> table = database.createTable("example_table", tableDefinition);
}
}
Instead of using the default type Row.class, you can define your own working object, which will be serialized as a Row.
This working object can be annotated when the field names do not exactly match the column names or when you want to fully describe your table to enable its creation solely from the entity definition.
The following example defines a Book class and then uses it to create the table.
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.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.mapping.Column;
import com.datastax.astra.client.tables.mapping.EntityTable;
import com.datastax.astra.client.tables.mapping.PartitionBy;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import lombok.Data;
public class Example {
@EntityTable("example_table")
@Data
public class Book {
@PartitionBy(0)
@Column(name = "title", type = TableColumnTypes.TEXT)
private String title;
@Column(name = "number_of_pages", type = TableColumnTypes.INT)
private Integer number_of_pages;
@PartitionBy(1)
@Column(name = "rating", type = TableColumnTypes.FLOAT)
private Float rating;
@Column(name = "genres", type = TableColumnTypes.SET, valueType = TableColumnTypes.TEXT)
private Set<String> genres;
@Column(
name = "metadata",
type = TableColumnTypes.MAP,
keyType = TableColumnTypes.TEXT,
valueType = TableColumnTypes.TEXT)
private Map<String, String> metadata;
@Column(name = "is_checked_out", type = TableColumnTypes.BOOLEAN)
private Boolean is_checked_out;
@Column(name = "due_date", type = TableColumnTypes.DATE)
private Date due_date;
}
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Table<Book> table = database.createTable(Book.class);
}
}
-
Typed tables
-
Untyped tables
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
// Define the type for the row
[TableName("TABLE_NAME")]
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnName("number_of_pages")]
public int? NumberOfPages { get; set; }
[ColumnPrimaryKey(2)]
[ColumnName("rating")]
public float Rating { get; set; }
[ColumnName("genres")]
public string[]? Genres { get; set; }
[ColumnName("metadata")]
public Dictionary<string, string>? Metadata { get; set; }
[ColumnName("is_checked_out")]
public bool? IsCheckedOut { get; set; }
[ColumnName("due_date")]
public DateOnly? DueDate { get; set; }
}
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var table = await database.CreateTableAsync<Book>();
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
using DataStax.AstraDB.DataApi.Utils;
namespace Examples;
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var definition = new TableDefinition()
.AddColumn("title", DataAPIType.Text())
.AddColumn("number_of_pages", DataAPIType.Int())
.AddColumn("rating", DataAPIType.Float())
.AddColumn("genres", DataAPIType.Set(DataAPIType.Text()))
.AddColumn(
"metadata",
DataAPIType.Map(DataAPIType.Text(), DataAPIType.Text())
)
.AddColumn("is_checked_out", DataAPIType.Boolean())
.AddColumn("due_date", DataAPIType.Date())
// Define the primary key for the table.
// In this case, the table uses a composite primary key.
.AddCompositePrimaryKey(new[] { "title", "rating" });
var table = await database.CreateTableAsync(
"TABLE_NAME",
definition
);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "example_table",
"definition": {
"columns": {
"title": {
"type": "text"
},
"number_of_pages": {
"type": "int"
},
"rating": {
"type": "float"
},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text"
},
"genres": {
"type": "set",
"valueType": "text"
},
"is_checked_out": {
"type": "boolean"
},
"due_date": {
"type": "date"
}
},
"primaryKey": {
"partitionBy": [
"title", "rating"
]
}
}
}
}'
Create a table with a compound primary key
A compound primary key is a primary key consisting of partition (grouping) columns and clustering (sorting) columns. For more information, see Primary keys in tables.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The Python client supports multiple ways to create a table.
In all cases, you must define the table schema, and then pass the definition to the create_table method.
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
-
CreateTableDefinition object
-
Fluent interface
-
Dictionary
You can define the table as a CreateTableDefinition and then build the table from the CreateTableDefinition object.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TableKeyValuedColumnType,
TableKeyValuedColumnTypeDescriptor,
TablePrimaryKeyDescriptor,
TableScalarColumnTypeDescriptor,
TableValuedColumnType,
TableValuedColumnTypeDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = CreateTableDefinition(
# Define all of the columns in the table
columns={
"title": TableScalarColumnTypeDescriptor(
column_type=ColumnType.TEXT
),
"number_of_pages": TableScalarColumnTypeDescriptor(
column_type=ColumnType.INT
),
"rating": TableScalarColumnTypeDescriptor(
column_type=ColumnType.FLOAT
),
"genres": TableValuedColumnTypeDescriptor(
column_type=TableValuedColumnType.SET,
value_type=ColumnType.TEXT,
),
"metadata": TableKeyValuedColumnTypeDescriptor(
column_type=TableKeyValuedColumnType.MAP,
key_type=ColumnType.TEXT,
value_type=ColumnType.TEXT,
),
"is_checked_out": TableScalarColumnTypeDescriptor(
column_type=ColumnType.BOOLEAN
),
"due_date": TableScalarColumnTypeDescriptor(
column_type=ColumnType.DATE
),
},
# Define the primary key for the table.
# In this case, the table uses a compound primary key.
primary_key=TablePrimaryKeyDescriptor(
partition_by=["title", "rating"],
partition_sort={
"number_of_pages": SortMode.ASCENDING,
"is_checked_out": SortMode.DESCENDING,
},
),
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can use a fluent interface to build the table definition and then create the table from the definition.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment, SortMode
from astrapy.info import ColumnType, CreateTableDefinition
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = (
CreateTableDefinition.builder()
# Define all of the columns in the table
.add_column("title", ColumnType.TEXT)
.add_column("number_of_pages", ColumnType.INT)
.add_column("rating", ColumnType.FLOAT)
.add_set_column(
"genres",
ColumnType.TEXT,
)
.add_map_column(
"metadata",
# This is the key type for the map column
ColumnType.TEXT,
# This is the value type for the map column
ColumnType.TEXT,
)
.add_column("is_checked_out", ColumnType.BOOLEAN)
.add_column("due_date", ColumnType.DATE)
# Define the primary key for the table.
# In this case, the table uses a compound primary key.
.add_partition_by(["title", "rating"])
.add_partition_sort(
{
"number_of_pages": SortMode.ASCENDING,
"is_checked_out": SortMode.DESCENDING,
}
)
# Finally, build the table definition.
.build()
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can define the table as a dictionary and then build the table from the dictionary.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
# Define the columns and primary key for the table
table_definition = {
"columns": {
"title": {"type": "text"},
"number_of_pages": {"type": "int"},
"rating": {"type": "float"},
"genres": {"type": "set", "valueType": "text"},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text",
},
"is_checked_out": {"type": "boolean"},
"due_date": {"type": "date"},
},
"primaryKey": {
"partitionBy": ["title", "rating"],
"partitionSort": {"number_of_pages": 1, "is_checked_out": -1},
},
}
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
The TypeScript client supports multiple ways to create a table. The method you choose depends on your typing preferences and whether you modified the ser/des configuration.
For more information, see Collection and table typing.
-
Automatic type inference
-
Manually typed tables
-
Untyped tables
The TypeScript client can automatically infer the TypeScript-equivalent type of the table’s schema and primary key.
To do this, first create the table definition.
Then, use InferTableSchema and InferTablePrimaryKey to infer the type of the table and of the primary key.
To create the table, provide the table definition and the inferred types to the createTable method.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
InferTablePrimaryKey,
InferTableSchema,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a compound primary key.
primaryKey: {
partitionBy: ["title", "rating"],
partitionSort: { number_of_pages: 1, is_checked_out: -1 },
},
});
// Infer the TypeScript-equivalent type of the table's schema and primary key
type TableSchema = InferTableSchema<typeof tableDefinition>;
type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;
(async function () {
// Provide the types and the definition
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
You can manually define the type for your table’s schema and primary key.
To create the table, provide the table definition and the types to the createTable method.
This may be necessary if you modify the table’s default ser/des configuration.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIDate,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a compound primary key.
primaryKey: {
partitionBy: ["title", "rating"],
partitionSort: { number_of_pages: 1, is_checked_out: -1 },
},
});
// Manually define the type of the table's schema and primary key
type TableSchema = {
title: string;
number_of_pages?: number | null | undefined;
rating?: number | null | undefined;
genres?: Set<string> | undefined;
metadata?: Map<string, string> | undefined;
is_checked_out?: boolean | null | undefined;
due_date?: DataAPIDate | null | undefined;
};
type TablePrimaryKey = Pick<TableSchema, "title" | "rating">;
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can use the TableSchema type as you would any other type.
For example, this gives a type error since the TableSchema type from the previous example does not include bad_field:
const row: TableSchema = {
title: "Wind with No Name",
number_of_pages: 193,
bad_field: "I will error",
};
To create a table without any typing, pass SomeRow as the single generic type parameter to the createTable method.
This types the table’s rows as Record<string, any>.
This is the most flexible but least type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
SomeRow,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
title: "text",
number_of_pages: "int",
rating: "float",
genres: { type: "set", valueType: "text" },
metadata: {
type: "map",
keyType: "text",
valueType: "text",
},
is_checked_out: "boolean",
due_date: "date",
},
// Define the primary key for the table.
// In this case, the table uses a compound primary key.
primaryKey: {
partitionBy: ["title", "rating"],
partitionSort: { number_of_pages: 1, is_checked_out: -1 },
},
});
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<SomeRow>("example_table", {
definition: tableDefinition,
keyspace: "KEYSPACE_NAME",
});
})();
The Java client supports multiple ways to create a table. In all cases, you must define the table schema.
-
Use a generic type
-
Define the row type
If you don’t specify the Class parameter when creating an instance of the generic class Table, the client defaults Table as the type.
In this case, the working object type T is Row.class.
import static com.datastax.astra.client.core.query.Sort.ascending;
import static com.datastax.astra.client.core.query.Sort.descending;
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.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.rows.Row;
public class Example {
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnText("title")
.addColumnInt("number_of_pages")
.addColumn("rating", TableColumnTypes.FLOAT)
.addColumnSet("genres", TableColumnTypes.TEXT)
.addColumnMap("metadata", TableColumnTypes.TEXT, TableColumnTypes.TEXT)
.addColumnBoolean("is_checked_out")
.addColumn("due_date", TableColumnTypes.DATE)
// Define the primary key for the table.
// In this case, the table uses a compound primary key.
.addPartitionBy("title")
.addPartitionBy("rating")
.addPartitionSort(ascending("number_of_pages"))
.addPartitionSort(descending("is_checked_out"));
Table<Row> table = database.createTable("example_table", tableDefinition);
}
}
Instead of using the default type Row.class, you can define your own working object, which will be serialized as a Row.
This working object can be annotated when the field names do not exactly match the column names or when you want to fully describe your table to enable its creation solely from the entity definition.
The following example defines a Book class and then uses it to create the table.
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.query.SortOrder;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.mapping.Column;
import com.datastax.astra.client.tables.mapping.EntityTable;
import com.datastax.astra.client.tables.mapping.PartitionBy;
import com.datastax.astra.client.tables.mapping.PartitionSort;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import lombok.Data;
public class Example {
@EntityTable("example_table")
@Data
public class Book {
@PartitionBy(0)
@Column(name = "title", type = TableColumnTypes.TEXT)
private String title;
@PartitionSort(position = 0, order = SortOrder.ASCENDING)
@Column(name = "number_of_pages", type = TableColumnTypes.INT)
private Integer number_of_pages;
@PartitionBy(1)
@Column(name = "rating", type = TableColumnTypes.FLOAT)
private Float rating;
@Column(name = "genres", type = TableColumnTypes.SET, valueType = TableColumnTypes.TEXT)
private Set<String> genres;
@Column(
name = "metadata",
type = TableColumnTypes.MAP,
keyType = TableColumnTypes.TEXT,
valueType = TableColumnTypes.TEXT)
private Map<String, String> metadata;
@PartitionSort(position = 1, order = SortOrder.DESCENDING)
@Column(name = "is_checked_out", type = TableColumnTypes.BOOLEAN)
private Boolean is_checked_out;
@Column(name = "due_date", type = TableColumnTypes.DATE)
private Date due_date;
}
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Table<Book> table = database.createTable(Book.class);
}
}
-
Typed tables
-
Untyped tables
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
// Define the type for the row
[TableName("TABLE_NAME")]
public class Book
{
[ColumnPrimaryKey(1)]
[ColumnName("title")]
public string Title { get; set; } = null!;
[ColumnPrimaryKeySort(1, SortDirection.Ascending)]
[ColumnName("number_of_pages")]
public int NumberOfPages { get; set; }
[ColumnPrimaryKey(2)]
[ColumnName("rating")]
public float Rating { get; set; }
[ColumnName("genres")]
public string[]? Genres { get; set; }
[ColumnName("metadata")]
public Dictionary<string, string>? Metadata { get; set; }
[ColumnPrimaryKeySort(2, SortDirection.Descending)]
[ColumnName("is_checked_out")]
public bool IsCheckedOut { get; set; }
[ColumnName("due_date")]
public DateOnly? DueDate { get; set; }
}
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var table = await database.CreateTableAsync<Book>();
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
using DataStax.AstraDB.DataApi.Utils;
namespace Examples;
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var definition = new TableDefinition()
.AddColumn("title", DataAPIType.Text())
.AddColumn("number_of_pages", DataAPIType.Int())
.AddColumn("rating", DataAPIType.Float())
.AddColumn("genres", DataAPIType.Set(DataAPIType.Text()))
.AddColumn(
"metadata",
DataAPIType.Map(DataAPIType.Text(), DataAPIType.Text())
)
.AddColumn("is_checked_out", DataAPIType.Boolean())
.AddColumn("due_date", DataAPIType.Date())
// Define the primary key for the table.
// In this case, the table uses a compound primary key.
.AddCompoundPrimaryKey(
new[] { "title", "rating" },
new[]
{
new PrimaryKeySort("number_of_pages", SortDirection.Ascending),
new PrimaryKeySort("is_checked_out", SortDirection.Descending),
}
);
var table = await database.CreateTableAsync(
"TABLE_NAME",
definition
);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "example_table",
"definition": {
"columns": {
"title": {
"type": "text"
},
"number_of_pages": {
"type": "int"
},
"rating": {
"type": "float"
},
"metadata": {
"type": "map",
"keyType": "text",
"valueType": "text"
},
"genres": {
"type": "set",
"valueType": "text"
},
"is_checked_out": {
"type": "boolean"
},
"due_date": {
"type": "date"
}
},
"primaryKey": {
"partitionBy": [
"title",
"rating"
],
"partitionSort": {
"number_of_pages": 1,
"is_checked_out": -1
}
}
}
}
}'
Create a table with a column to store vector embeddings
If you want to store pre-generated vector embeddings in a table, create a table with a vector column. A table can include more than one vector column.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The Python client supports multiple ways to create a table.
In all cases, you must define the table schema, and then pass the definition to the create_table method.
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
-
CreateTableDefinition object
-
Fluent interface
-
Dictionary
You can define the table as a CreateTableDefinition and then build the table from the CreateTableDefinition object.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TablePrimaryKeyDescriptor,
TableScalarColumnTypeDescriptor,
TableVectorColumnTypeDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = CreateTableDefinition(
# Define all of the columns in the table
columns={
"example_vector": TableVectorColumnTypeDescriptor(
dimension=1024,
),
"example_non_vector": TableScalarColumnTypeDescriptor(
column_type=ColumnType.TEXT
),
},
# Define the primary key for the table.
# In this case, the table uses a single-column primary key.
primary_key=TablePrimaryKeyDescriptor(
partition_by=["example_non_vector"], partition_sort={}
),
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can use a fluent interface to build the table definition and then create the table from the definition.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import ColumnType, CreateTableDefinition
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = (
CreateTableDefinition.builder()
# Define all of the columns in the table
.add_vector_column("example_vector", dimension=1024)
.add_column("example_non_vector", ColumnType.TEXT)
# Define the primary key for the table.
# In this case, the table uses a single-column primary key.
.add_partition_by(["example_non_vector"])
# Finally, build the table definition.
.build()
)
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
You can define the table as a dictionary and then build the table from the dictionary.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
# Define the columns and primary key for the table
table_definition = {
"columns": {
"example_vector": {"type": "vector", "dimension": 1024},
"example_non_vector": {"type": "text"},
},
"primaryKey": {
"partitionBy": ["example_non_vector"],
"partitionSort": {},
},
}
table = database.create_table(
"example_table",
keyspace="KEYSPACE_NAME",
definition=table_definition,
)
The TypeScript client supports multiple ways to create a table. The method you choose depends on your typing preferences and whether you modified the ser/des configuration.
For more information, see Collection and table typing.
-
Automatic type inference
-
Manually typed tables
-
Untyped tables
The TypeScript client can automatically infer the TypeScript-equivalent type of the table’s schema and primary key.
To do this, first create the table definition.
Then, use InferTableSchema and InferTablePrimaryKey to infer the type of the table and of the primary key.
To create the table, provide the table definition and the inferred types to the createTable method.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
InferTablePrimaryKey,
InferTableSchema,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
example_vector: { type: "vector", dimension: 1024 },
example_non_vector: "text",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["example_non_vector"],
},
});
// Infer the TypeScript-equivalent type of the table's schema and primary key
type TableSchema = InferTableSchema<typeof tableDefinition>;
type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;
(async function () {
// Provide the types and the definition
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can manually define the type for your table’s schema and primary key.
To create the table, provide the table definition and the types to the createTable method.
This may be necessary if you modify the table’s default ser/des configuration.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIVector,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
example_vector: { type: "vector", dimension: 1024 },
example_non_vector: "text",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["example_non_vector"],
},
});
// Manually define the type of the table's schema and primary key
type TableSchema = {
example_vector: DataAPIVector;
example_non_vector: string;
};
type TablePrimaryKey = Pick<TableSchema, "example_non_vector">;
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
To create a table without any typing, pass SomeRow as the single generic type parameter to the createTable method.
This types the table’s rows as Record<string, any>.
This is the most flexible but least type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
SomeRow,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
example_vector: { type: "vector", dimension: 1024 },
example_non_vector: "text",
},
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
primaryKey: {
partitionBy: ["example_non_vector"],
},
});
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<SomeRow>("example_table", {
definition: tableDefinition,
keyspace: "KEYSPACE_NAME",
});
})();
The Java client supports multiple ways to create a table. In all cases, you must define the table schema.
-
Use a generic type
-
Define the row type
If you don’t specify the Class parameter when creating an instance of the generic class Table, the client defaults Table as the type.
In this case, the working object type T is Row.class.
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.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnDefinitionVector;
import com.datastax.astra.client.tables.definition.rows.Row;
public class Example {
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnVector("example_vector", new TableColumnDefinitionVector().dimension(1024))
.addColumnText("example_non_vector")
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
.addPartitionBy("example_non_vector");
Table<Row> table = database.createTable("example_table", tableDefinition);
}
}
Instead of using the default type Row.class, you can define your own working object, which will be serialized as a Row.
This working object can be annotated when the field names do not exactly match the column names or when you want to fully describe your table to enable its creation solely from the entity definition.
The following example defines a Book class and then uses it to create the table.
import com.datastax.astra.client.DataAPIClients;
import com.datastax.astra.client.core.vector.DataAPIVector;
import com.datastax.astra.client.databases.Database;
import com.datastax.astra.client.tables.Table;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.mapping.Column;
import com.datastax.astra.client.tables.mapping.ColumnVector;
import com.datastax.astra.client.tables.mapping.EntityTable;
import com.datastax.astra.client.tables.mapping.PartitionBy;
import lombok.Data;
public class Example {
@EntityTable("example_table")
@Data
public class Book {
@ColumnVector(name = "example_vector", dimension = 1024)
private DataAPIVector vector;
@PartitionBy(0)
@Column(name = "example_non_vector", type = TableColumnTypes.TEXT)
private String exampleNonVector;
}
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Table<Book> table = database.createTable(Book.class);
}
}
-
Typed tables
-
Untyped tables
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
// Define the type for the row
[TableName("TABLE_NAME")]
public class ExampleRow
{
[ColumnPrimaryKey]
[ColumnName("example_non_vector")]
public string ExampleNonVector { get; set; } = null!;
[ColumnVector(1024)]
[ColumnName("example_vector")]
public float[]? ExampleVector { get; set; }
}
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var table = await database.CreateTableAsync<ExampleRow>();
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
using DataStax.AstraDB.DataApi.Utils;
namespace Examples;
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var definition = new TableDefinition()
.AddColumn("example_vector", DataAPIType.Vector(1024))
.AddColumn("example_non_vector", DataAPIType.Text())
// Define the primary key for the table.
// In this case, the table uses a single-column primary key.
.AddSinglePrimaryKey("example_non_vector");
var table = await database.CreateTableAsync(
"TABLE_NAME",
definition
);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "example_table",
"definition": {
"columns": {
"example_vector": {
"type": "vector",
"dimension": 1024
},
"example_non_vector": {
"type": "text"
}
},
"primaryKey": "example_non_vector"
}
}
}'
Create a table that uses a user-defined type (UDT)
In addition to the supported types, you can create a user-defined type to use in your table.
You can use a user-defined type as the type of a column or as the value type of a map, list, or set column. You can’t use a user-defined type as the key type of a map column or as a partitionKey or clustering key.
The following examples demonstrate how to use a user-defined type called person for the group_leader column, value type in the group_members set column, and value type in the group_roles map column.
-
Python
-
TypeScript
-
Java
-
C#
-
curl
The Python client supports multiple ways to create a table.
In all cases, you must define the table schema, and then pass the definition to the create_table method.
The following example uses untyped documents or rows, but you can define a client-side type for your collection to help statically catch errors. For examples, see Typing support.
-
CreateTableDefinition object
-
Fluent interface
-
Dictionary
You can define the table as a CreateTableDefinition and then build the table from the CreateTableDefinition object.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TableKeyValuedColumnType,
TableKeyValuedColumnTypeDescriptor,
TablePrimaryKeyDescriptor,
TableScalarColumnTypeDescriptor,
TableUDTColumnDescriptor,
TableValuedColumnType,
TableValuedColumnTypeDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = CreateTableDefinition(
# Define all of the columns in the table
columns={
"id": TableScalarColumnTypeDescriptor(
column_type=ColumnType.UUID
),
"group_leader": TableUDTColumnDescriptor(udt_name="person"),
"group_members": TableValuedColumnTypeDescriptor(
column_type=TableValuedColumnType.SET,
value_type=TableUDTColumnDescriptor(
udt_name="person",
),
),
"group_roles": TableKeyValuedColumnTypeDescriptor(
column_type=TableKeyValuedColumnType.MAP,
key_type=ColumnType.TEXT,
value_type=TableUDTColumnDescriptor(
udt_name="person",
),
),
},
primary_key=TablePrimaryKeyDescriptor(
partition_by=["id"], partition_sort={}
),
)
table = database.create_table(
"example_table",
definition=table_definition,
keyspace="KEYSPACE_NAME",
)
You can use a fluent interface to build the table definition and then create the table from the definition.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.info import (
ColumnType,
CreateTableDefinition,
TableUDTColumnDescriptor,
)
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
table_definition = (
CreateTableDefinition.builder()
# Define all of the columns in the table
.add_scalar_column("id", ColumnType.UUID)
.add_userdefinedtype_column("group_leader", udt_name="person")
.add_set_column(
"group_members",
value_type=TableUDTColumnDescriptor(
udt_name="person",
),
)
.add_map_column(
"group_roles",
key_type=ColumnType.TEXT,
value_type=TableUDTColumnDescriptor(
udt_name="person",
),
)
# Define the primary key for the table.
.add_partition_by(["id"])
# Finally, build the table definition.
.build()
)
table = database.create_table(
"example_table",
definition=table_definition,
keyspace="KEYSPACE_NAME",
)
You can define the table as a dictionary and then build the table from the dictionary.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
# Get an existing database
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
)
# Define the columns and primary key for the table
table_definition = {
"columns": {
"id": {"type": "uuid"},
"group_leader": {
"type": "userDefined",
"udtName": "person",
},
"group_members": {
"type": "set",
"valueType": {
"type": "userDefined",
"udtName": "person",
},
},
"group_roles": {
"type": "map",
"keyType": "text",
"valueType": {
"type": "userDefined",
"udtName": "person",
},
},
},
"primaryKey": {
"partitionBy": ["id"],
"partitionSort": {},
},
}
table = database.create_table(
"example_table",
definition=table_definition,
keyspace="KEYSPACE_NAME",
)
The TypeScript client supports multiple ways to create a table. The method you choose depends on your typing preferences and whether you modified the ser/des configuration.
For more information, see Collection and table typing.
-
Automatic type inference
-
Manually typed tables
-
Untyped tables
The TypeScript client can automatically infer the TypeScript-equivalent type of the table’s schema and primary key.
To do this, first create the table definition.
Then, use InferTableSchema and InferTablePrimaryKey to infer the type of the table and of the primary key.
To create the table, provide the table definition and the inferred types to the createTable method.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
InferTablePrimaryKey,
InferTableSchema,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
id: "uuid",
group_leader: {
type: "userDefined",
udtName: "person",
},
group_members: {
type: "set",
valueType: {
type: "userDefined",
udtName: "person",
},
},
group_roles: {
type: "map",
keyType: "text",
valueType: {
type: "userDefined",
udtName: "person",
},
},
},
// Define the primary key for the table.
primaryKey: {
partitionBy: ["id"],
},
});
// Infer the TypeScript-equivalent type of the table's schema and primary key
type TableSchema = InferTableSchema<typeof tableDefinition>;
type TablePrimaryKey = InferTablePrimaryKey<typeof tableDefinition>;
(async function () {
// Provide the types and the definition
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
You can manually define the type for your table’s schema and primary key.
To create the table, provide the table definition and the types to the createTable method.
This may be necessary if you modify the table’s default ser/des configuration.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
DataAPIDate,
Table,
UUID,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
id: "uuid",
group_leader: {
type: "userDefined",
udtName: "person",
},
group_members: {
type: "set",
valueType: {
type: "userDefined",
udtName: "person",
},
},
group_roles: {
type: "map",
keyType: "text",
valueType: {
type: "userDefined",
udtName: "person",
},
},
},
// Define the primary key for the table.
primaryKey: {
partitionBy: ["id"],
},
});
// Manually define the type of the table's schema and primary key
type Person = { name: string; level: number };
type TableSchema = {
id: UUID;
group_leader: Person;
group_members: Set<Person>;
group_roles: Map<string, Person>;
};
type TablePrimaryKey = Pick<TableSchema, "id">;
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<TableSchema, TablePrimaryKey>(
"example_table",
{ definition: tableDefinition, keyspace: "KEYSPACE_NAME" },
);
})();
To create a table without any typing, pass SomeRow as the single generic type parameter to the createTable method.
This types the table’s rows as Record<string, any>.
This is the most flexible but least type-safe option.
import {
DataAPIClient,
UsernamePasswordTokenProvider,
SomeRow,
Table,
} from "@datastax/astra-db-ts";
// Get an existing database
const client = new DataAPIClient({ environment: "hcd" });
const database = client.db("API_ENDPOINT", {
token: new UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
});
const tableDefinition = Table.schema({
// Define all of the columns in the table
columns: {
id: "uuid",
group_leader: {
type: "userDefined",
udtName: "person",
},
group_members: {
type: "set",
valueType: {
type: "userDefined",
udtName: "person",
},
},
group_roles: {
type: "map",
keyType: "text",
valueType: {
type: "userDefined",
udtName: "person",
},
},
},
// Define the primary key for the table.
primaryKey: {
partitionBy: ["id"],
},
});
(async function () {
// Provide the types and the definition to create the table
const table = await database.createTable<SomeRow>("example_table", {
definition: tableDefinition,
keyspace: "KEYSPACE_NAME",
});
})();
The Java client supports multiple ways to create a table. In all cases, you must define the table schema.
-
Use a generic type
-
Define the row type
If you don’t specify the Class parameter when creating an instance of the generic class Table, the client defaults Table as the type.
In this case, the working object type T is Row.class.
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.definition.TableDefinition;
import com.datastax.astra.client.tables.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.rows.Row;
public class Example {
public static void main(String[] args) {
// Get an existing database
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
TableDefinition tableDefinition =
new TableDefinition()
// Define all of the columns in the table
.addColumnUuid("id")
.addColumnUserDefinedType("group_leader", "person")
.addColumnSetUserDefinedType("group_members", "person")
.addColumnMapUserDefinedType("group_roles", "person", TableColumnTypes.TEXT)
// Define the primary key for the table.
.addPartitionBy("id");
Table<Row> table = database.createTable("example_table", tableDefinition);
}
}
Instead of using the default type Row.class, you can define your own working object, which will be serialized as a Row.
This working object can be annotated when the field names do not exactly match the column names or when you want to fully describe your table to enable its creation solely from the entity definition.
The following example defines a Book class and then uses it to create the table.
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.definition.columns.TableColumnTypes;
import com.datastax.astra.client.tables.definition.types.TableUserDefinedType;
import com.datastax.astra.client.tables.mapping.Column;
import com.datastax.astra.client.tables.mapping.EntityTable;
import com.datastax.astra.client.tables.mapping.PartitionBy;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import lombok.Data;
public class Example {
// Define the user-defined type "person"
@TableUserDefinedType("person")
public class Person {
@Column(name = "user_name", type = TableColumnTypes.TEXT)
private String userName;
@Column(name = "age", type = TableColumnTypes.INT)
private Integer age;
}
// Define the table
@EntityTable("example_table")
@Data
class Group {
@PartitionBy(0)
@Column(name = "id", type = TableColumnTypes.UUID)
private UUID id;
@Column(name = "group_leader", type = TableColumnTypes.USERDEFINED, udtName = "person")
private Person groupLeader;
@Column(
name = "group_members",
type = TableColumnTypes.SET,
valueType = TableColumnTypes.USERDEFINED,
udtName = "person")
private Set<Person> groupMembers;
@Column(
name = "group_roles",
type = TableColumnTypes.MAP,
keyType = TableColumnTypes.TEXT,
valueType = TableColumnTypes.USERDEFINED,
udtName = "person")
private Map<String, Person> groupRoles;
}
public static void main(String[] args) {
Database database =
DataAPIClients.clientHCD("USERNAME", "PASSWORD")
.getDatabase("API_ENDPOINT", "KEYSPACE_NAME");
Table<Group> table = database.createTable(Group.class);
}
}
-
Typed tables
-
Untyped tables
You can manually define a client-side type for your table to help statically catch errors. For more information and examples, see Custom typing for tables.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
namespace Examples;
// Define the user-defined type
// The type will be created if a type
// with the same name does not already exist
[UserDefinedType("person")]
public class Person
{
[ColumnName("name")]
public string? Name { get; set; }
[ColumnName("level")]
public int? Level { get; set; }
};
// Define the type for the row
[TableName("TABLE_NAME")]
public class ExampleRow
{
[ColumnPrimaryKey]
[ColumnName("id")]
public Guid Id { get; set; }
[ColumnName("group_leader")]
public Person? GroupLeader { get; set; }
[ColumnName("group_members")]
public Person[]? GroupMembers { get; set; }
[ColumnName("group_roles")]
public Dictionary<string, Person>? GroupRoles { get; set; }
}
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var table = await database.CreateTableAsync<ExampleRow>();
}
}
If you don’t pass a type parameter, the collection or table remains untyped. This is a more flexible but less type-safe option.
using DataStax.AstraDB.DataApi;
using DataStax.AstraDB.DataApi.Core;
using DataStax.AstraDB.DataApi.Tables;
using DataStax.AstraDB.DataApi.Utils;
namespace Examples;
public class Program
{
static async Task Main()
{
// Instantiate the client
var client = new DataAPIClient(
new CommandOptions() { Destination = DataAPIDestination.HCD }
);
// Connect to a database
var database = client.GetDatabase(
"API_ENDPOINT",
DataAPIClient.UsernamePasswordTokenProvider(
"USERNAME",
"PASSWORD"
),
"KEYSPACE_NAME"
);
// Create a table
var definition = new TableDefinition()
.AddColumn("id", DataAPIType.Uuid())
.AddColumn("group_leader", DataAPIType.UserDefined("person"))
.AddColumn(
"group_members",
DataAPIType.Set(DataAPIType.UserDefined("person"))
)
.AddColumn(
"group_roles",
DataAPIType.Map(
DataAPIType.Text(),
DataAPIType.UserDefined("person")
)
)
.AddSinglePrimaryKey("id");
var table = await database.CreateTableAsync(
"TABLE_NAME",
definition
);
}
}
curl -sS -L -X POST "API_ENDPOINT/v1/KEYSPACE_NAME" \
--header "Token: APPLICATION_TOKEN" \
--header "Content-Type: application/json" \
--data '{
"createTable": {
"name": "example_table",
"definition": {
"columns": {
"id": {
"type": "uuid"
},
"group_leader": {
"type": "userDefined",
"udtName": "person"
},
"group_members": {
"type": "set",
"valueType": {
"type": "userDefined",
"udtName": "person"
}
},
"group_roles": {
"type": "map",
"keyType": "text",
"valueType": {
"type": "userDefined",
"udtName": "person"
}
}
},
"primaryKey": "id"
}
}
}'
Client reference
-
Python
-
TypeScript
-
Java
-
C#
-
curl
For more information, see the client reference.
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.