Insert a row

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.

Inserts a single row into a table.

This method can insert a row in an existing CQL table, but the Data API does not support all CQL data types or modifiers. For more information, see Data types in tables.

For general information about working with tables and rows, see About tables.

Method signature

  • Python

  • TypeScript

  • Java

  • curl

The following method belongs to the astrapy.Table class.

insert_one(
  row: Dict[str, Any],
  *,
  general_method_timeout_ms: int,
  request_timeout_ms: int,
  timeout_ms: int,
) -> TableInsertOneResult:

The following method belongs to the Table class.

async insertOne(
  row: WSchema,
  timeout?: number | TimeoutDescriptor,
): TableInsertOneResult<PKey>

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

TableInsertOneResult insertOne(T row)
TableInsertOneResult insertOne(
  T row,
  TableInsertOneOptions insertOneOptions
)
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 '{
  "insertOne": {
    "document": ROW
  }
}'

Result

  • Python

  • TypeScript

  • Java

  • curl

Inserts the specified row and returns a TableInsertOneResult object that includes the primary key of the inserted row as a dictionary and as a tuple.

If a row with the specified primary key already exists in the table, the row will be overwritten with the specified column values. Unspecified columns will remain unchanged.

If any of the inserted columns use the wrong datatype or improper encoding, then the entire insert fails.

Example response:

TableInsertOneResult(
  inserted_id={'match_id': 'match_0', 'round': 1},
  inserted_id_tuple=('match_0', 1),
  raw_results=...
)

Inserts the specified row and returns a promise that resolves to a TableInsertOneResult<PKey> object that includes the primary key of the inserted row. The primary key type is inferred from the PKey of the table’s type. If it cannot be inferred from the PKey, it is instead inferred from Partial<RSchema>.

If a row with the specified primary key already exists in the table, the row will be overwritten with the specified column values. Unspecified columns will remain unchanged.

If any of the inserted columns use the wrong datatype or improper encoding, then the entire insert fails.

Example response:

{
  insertedId: { matchId: 'match_0', round: 1 },
}

Inserts the specified row and returns a TableInsertOneResult instance that includes the primary key of the inserted row and the schema of the primary key.

If a row with the specified primary key already exists in the table, the row will be overwritten with the specified column values. Unspecified columns will remain unchanged.

If any of the inserted columns use the wrong datatype or improper encoding, then the entire insert fails.

Example response:

{
  "status": {
    "primaryKeySchema": {
      "match_id": {
        "type": "text"
      },
      "round": {
        "type": "int"
      }
    },
    "insertedIds": [
      [
        "match_1",
        2
      ]
    ]
  }
}

Inserts the specified row. In the JSON response, status.primaryKeySchema is an object that describes the table’s primary key definition, including column names and types. status.insertedIds is a nested array that contains the values inserted for each primary key column.

If a row with the specified primary key already exists in the table, the row will be overwritten with the specified column values. Unspecified columns will remain unchanged.

If any of the inserted columns use the wrong datatype or improper encoding, then the entire insert fails.

Example response for a single-column primary key:

{
  "status": {
    "primaryKeySchema": {
      "email": {
        "type": "ascii"
      }
    },
    "insertedIds": [
      [
        "tal@example.com"
      ]
    ]
  }
}

Example response for a multi-column primary key:

{
  "status": {
    "primaryKeySchema": {
      "email": {
        "type": "ascii"
      },
      "graduation_year": {
        "type": "int"
      }
    },
    "insertedIds": [
      [
        "tal@example.com",
        2014
      ]
    ]
  }
}

Parameters

  • Python

  • TypeScript

  • Java

  • curl

Name Type Summary

row

dict

Defines the row to insert. Contains key-value pairs for each column in the table. At minimum, primary key values are required. Any unspecified columns are set to null.

The table definition determines the available columns, the primary key, and each column’s type. For more information, see Create a table and Data types in tables.

general_method_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

row

Schema

Defines the row to insert. Contains key-value pairs for each column in the table. At minimum, primary key values are required. Any unspecified columns are set to null.

The table definition determines the available columns, the primary key, and each column’s type. For more information, see Create a table and Data types in tables.

timeout?

WithTimeout

The client-side timeout for this operation.

Name Type Summary

row

Row

Defines the row to insert. This object is similar to a Map where you can add the object you like with utilities methods. At minimum, you must specify the primary key values in full. Any unspecified columns are set to null.

The table definition determines the available columns, the primary key, and each column’s type. For more information, see Create a table and Data types in tables.

options

TableInsertOneOptions

Specialization of the Table object overriding default configuration (DataAPIOptions)

Name Type Summary

insertOne

command

Data API command to insert one row in a table.

document

object

Defines the row to insert. Contains key-value pairs for each column in the table. At minimum, primary key values are required. Any unspecified columns are set to null.

The table definition determines the available columns, the primary key, and each column’s type. For more information, see Create a table and Data types in tables.

Examples

The following examples demonstrate how to insert a row into a table.

  • Python

  • TypeScript

  • Java

  • curl

Insert a row with values specified for all columns:

insert_result = my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "m_vector": DataAPIVector([0.4, -0.6, 0.2]),
        "score": 18,
        "when": DataAPITimestamp.from_string("2024-11-28T11:30:00Z"),
        "winner": "Victor",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
        ]),
    },
)

Insert a row with values specified for some columns and unspecified columns set to null:

my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "winner": "Victor Vector",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
            UUID("0193539a-2880-8875-9f07-222222222222"),
        ]),
    },
)
Full example script
from astrapy import DataAPIClient
client = DataAPIClient("TOKEN")
database = client.get_database("API_ENDPOINT")

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

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

# a full-row insert using astrapy's datatypes
from astrapy.data_types import (
    DataAPISet,
    DataAPITimestamp,
    DataAPIVector,
)
from astrapy.ids import UUID

insert_result = my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "m_vector": DataAPIVector([0.4, -0.6, 0.2]),
        "score": 18,
        "when": DataAPITimestamp.from_string("2024-11-28T11:30:00Z"),
        "winner": "Victor",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
        ]),
    },
)
insert_result.inserted_id
# {'match_id': 'match_0', 'round': 1}
insert_result.inserted_id_tuple
# ('match_0', 1)

# a partial-row (which in this case overwrites some of the values)
my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "winner": "Victor Vector",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
            UUID("0193539a-2880-8875-9f07-222222222222"),
        ]),
    },
)
# TableInsertOneResult(inserted_id={'match_id': 'match_0', 'round': 1} ...

# another insertion demonstrating standard-library datatypes in values
import datetime

my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 2,
        "winner": "Angela",
        "score": 25,
        "when": datetime.datetime(
            2024, 7, 13, 12, 55, 30, 889,
            tzinfo=datetime.timezone.utc,
        ),
        "fighters": {
            UUID("019353cb-8e01-8276-a190-333333333333"),
        },
        "m_vector": [0.4, -0.6, 0.2],
    },
)
# TableInsertOneResult(inserted_id={'match_id': 'match_0', 'round': 2}, ...

Example:

# a full-row insert using astrapy's datatypes
from astrapy.data_types import (
    DataAPISet,
    DataAPITimestamp,
    DataAPIVector,
)
from astrapy.ids import UUID

insert_result = my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "m_vector": DataAPIVector([0.4, -0.6, 0.2]),
        "score": 18,
        "when": DataAPITimestamp.from_string("2024-11-28T11:30:00Z"),
        "winner": "Victor",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
        ]),
    },
)
insert_result.inserted_id
# {'match_id': 'match_0', 'round': 1}
insert_result.inserted_id_tuple
# ('match_0', 1)

# a partial-row (which in this case overwrites some of the values)
my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 1,
        "winner": "Victor Vector",
        "fighters": DataAPISet([
            UUID("0193539a-2770-8c09-a32a-111111111111"),
            UUID("0193539a-2880-8875-9f07-222222222222"),
        ]),
    },
)
# TableInsertOneResult(inserted_id={'match_id': 'match_0', 'round': 1} ...

# another insertion demonstrating standard-library datatypes in values
import datetime

my_table.insert_one(
    {
        "match_id": "match_0",
        "round": 2,
        "winner": "Angela",
        "score": 25,
        "when": datetime.datetime(
            2024, 7, 13, 12, 55, 30, 889,
            tzinfo=datetime.timezone.utc,
        ),
        "fighters": {
            UUID("019353cb-8e01-8276-a190-333333333333"),
        },
        "m_vector": [0.4, -0.6, 0.2],
    },
)
# TableInsertOneResult(inserted_id={'match_id': 'match_0', 'round': 2}, ...

Insert a row with only the primary keys specified and all other columns set to null:

await table.insertOne({ matchId: 'match_0', round: 1 });

Insert a row with values for all columns:

await table.insertOne({
  matchId: 'match_0',
  round: 1,
  score: 18,
  when: timestamp(),
  winner: 'Victor',
  fighters: new Set([
    uuid('a4e4e5b0-1f3b-4b4d-8e1b-4e6b3f1f3b4d'),
    uuid(4),
  ]),
  mVector: vector([0.2, -0.3, -0.5]),
});

Example:

Full script
import { CreateTableDefinition, DataAPIClient, InferTablePrimaryKey, InferTableSchema, timestamp, uuid, vector } 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, and then infer the type.
// For information about table typing and definitions, 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;

type TableSchema = InferTableSchema<typeof TableDefinition>;
type TablePK = InferTablePrimaryKey<typeof TableDefinition>;

(async function () {
  // Create a table with the given TableSchema type if a 'games' table doesn't already exist
  const table = await db.createTable<TableSchema, TablePK>('games', { definition: TableDefinition, ifNotExists: true });

// Use insertOne and insertMany to insert rows into tables.
// Inserts are also upserts for tables.

// insertOne examples

  // Inserts a single row
  const res = await table.insertOne({
      matchId: 'match_0',
      round: 1,                                       // All non-varint/decimal numbers are represented as JS numbers
      score: 18,
      when: timestamp(),                              // Shorthand for new DataAPITimestamp(new Date())
      winner: 'Victor',
      fighters: new Set([                             // Use native Maps, Sets, and Arrays for maps, sets, and lists.
        uuid('a4e4e5b0-1f3b-4b4d-8e1b-4e6b3f1f3b4d'), // You can nest datatypes in maps, sets, and lists.
        uuid(4),                                      // Shorthand for UUID.v4()
      ]),
      mVector: vector([0.2, -0.3, -0.5]),             // Shorthand for new DataAPIVector([0.2, -0.3, -0.5])
    });                                               // Use this instead of plain arrays to enable vector-specific optimizations

  // Returns primary key of type { id: string, time: DataAPITimestamp }
  const primaryKey = res.insertedId;
  console.log(primaryKey.matchId);

  // Inserts are also upserts in tables.
  // If the winner of round 1 was actually 'Cham P. Yun' instead of 'Victor',
  // you can use insertOne to modify the row identified by its primary key.
  await table.insertOne({
    matchId: 'match_0',
    round: 1,
    score: null,                // Set score to null to clear the previously inserted value
    winner: 'Cham P. Yun',
    mVector: [-0.6, 0.2, -0.7],
    });

  // The upserted row now has the following values:
  // { matchId: 'match_0', round: 1, score: null, when: <timestamp>, winner: 'Cham P. Yun', fighters: <uuid[]>, mVector: [-0.6, 0.2, -0.7] }

// insertMany examples

  // Inserts two rows in an unordered fashion.
  // Primary keys are required.
  // Unspecified columns are set to null.
  await table.insertMany([{
    matchId: 'fight4',
    round: 1,
    winner: 'Victor',
    score: 18,
    when: timestamp('2024-11-28T11:30:00Z'),
    fighters: new Set([
      uuid('0193539a-2770-8c09-a32a-111111111111'),
      uuid('019353e3-00b4-83f9-a127-222222222222'),
    ]),
    mVector: vector([0.4, -0.6, 0.2]),
    },
  // Insert with the primary key and 2 other values.
    {
    matchId: 'challenge6',
    round: 2,
    winner: 'Wynn Uhr',
    },
  ]);

  // Performs two inserts against the same row in an ordered fashion ('ordered: true').
  // Because inserts are also upserts in tables, if an ordered insert modifies the same row multiple times,
  // subsequent inserts overwrite prior inserts if the inserts modify the same columns.
  // In this example, the second insert overwrites the winner and mVector values from the first insert.
  //
  // In unordered inserts, upserts still occur, but the order is not guaranteed and the outcome is unpredictable.
  // However, unordered inserts are parallelized on the client and server.
  // They are generally more performant and recommended for most use cases.
  const res = await table.insertMany([
    {
      matchId: 'match_0',
      round: 1,                                       // All numbers are represented as JS numbers except varint and decimal
      score: 18,
      when: timestamp(),                              // Shorthand for new DataAPITimestamp(new Date())
      winner: 'Victor',
      fighters: new Set([                             // Use native Maps, Sets, and Arrays for maps, sets, and lists.
        uuid('a4e4e5b0-1f3b-4b4d-8e1b-4e6b3f1f3b4d'), // You can nest datatypes in maps, sets, and lists.
        uuid(7),                                      // Shorthand for UUID.v7()
      ]),
      mVector: vector([0.2, -0.3, -0.5]),             // Shorthand for new DataAPIVector([0.2, -0.3, -0.5])
    },                                                // Use this instead of plain arrays to enable vector-specific optimizations
    {
      matchId: 'match_0',
      round: 1,
      score: null,                                   // Set score to null to insert no value or clear a previously-inserted value
      winner: 'Cham P. Yun',
      mVector: [-0.6, 0.2, -0.7],
    }],
    {
      timeout: 60000,
      ordered: true,
    });

  // Returns primary key of type { matchId: string, round: number }[]
  // Because both inserts have the same matchId, the primary key is 'match_0' for both
  const primaryKey = res.insertedIds;
  console.log(primaryKey[0].matchId, primaryKey[1].matchId);

  // After both inserts, the row has the following values:
  // { matchId: 'match_0', round: 1, score: null, when: <timestamp>, winner: 'Cham P. Yun', fighters: <uuid[]>, mVector: [-0.6, 0.2, -0.7] }

  const docs: TableSchema[] = Array.from({ length: 101 }, (_, i) => ({
    matchId: `match_${i}`,
    round: 1,
  }));
  await table.insertMany(docs);

  // Uncomment the following line to drop the table and any related indexes.
  // await table.drop();
})();
// Inserts a single row
const res = await table.insertOne({
    matchId: 'match_0',
    round: 1,                                       // All non-varint/decimal numbers are represented as JS numbers
    score: 18,
    when: timestamp(),                              // Shorthand for new DataAPITimestamp(new Date())
    winner: 'Victor',
    fighters: new Set([                             // Use native Maps, Sets, and Arrays for maps, sets, and lists.
      uuid('a4e4e5b0-1f3b-4b4d-8e1b-4e6b3f1f3b4d'), // You can nest datatypes in maps, sets, and lists.
      uuid(4),                                      // Shorthand for UUID.v4()
    ]),
    mVector: vector([0.2, -0.3, -0.5]),             // Shorthand for new DataAPIVector([0.2, -0.3, -0.5])
  });                                               // Use this instead of plain arrays to enable vector-specific optimizations

// Returns primary key of type { id: string, time: DataAPITimestamp }
const primaryKey = res.insertedId;
console.log(primaryKey.matchId);

// Inserts are also upserts in tables.
// If the winner of round 1 was actually 'Cham P. Yun' instead of 'Victor',
// you can use insertOne to modify the row identified by its primary key.
await table.insertOne({
  matchId: 'match_0',
  round: 1,
  score: null,                // Set score to null to clear the previously inserted value
  winner: 'Cham P. Yun',
  mVector: [-0.6, 0.2, -0.7],
  });

// The upserted row now has the following values:
// { matchId: 'match_0', round: 1, score: null, when: <timestamp>, winner: 'Cham P. Yun', fighters: <uuid[]>, mVector: [-0.6, 0.2, -0.7] }

Insert a row with a value for every column:

Table<Row> table = db.getTable("games");
table.insertOne(new Row()
  .addText("match_id", "match_0")
  .addInt("round", 1)
  .addVector("m_vector", new DataAPIVector(new float[]{0.4f, -0.6f, 0.2f}))
  .addInt("score", 18)
  .addTimeStamp("when", Instant.now())
  .addText("winner", "Victor")
  .addSet("fighters", Set
   .of(UUID.fromString("0193539a-2770-8c09-a32a-111111111111"))));

Insert a row with some columns specified and unspecified columns set to null:

Table<Row> table = db.getTable("games");
table.insertOne(new Row()
  .addText("match_id", "match_0")
  .addInt("round", 1)
  .addText("winner", "Victor Vector")
  .addSet("fighters", Set
   .of(UUID.fromString("0193539a-2770-8c09-a32a-111111111111"),
       UUID.fromString("0193539a-2880-8875-9f07-222222222222")
    )
  )
);

Example:

package com.datastax.astra.client.tables;

import com.datastax.astra.client.DataAPIClient;
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.commands.results.TableInsertOneResult;
import com.datastax.astra.client.tables.definition.columns.ColumnDefinition;
import com.datastax.astra.client.tables.definition.rows.Row;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class InsertRow {
  public static void main(String[] args) {
   Database db = new DataAPIClient("token").getDatabase("endpoint");
   Table<Row> table = db.getTable("games");
   TableInsertOneResult result = table.insertOne(new Row()
     .addText("match_id", "mtch_0")
     .addInt("round", 1)
     .addVector("m_vector", new DataAPIVector(new float[]{0.4f, -0.6f, 0.2f}))
     .addInt("score", 18)
     .addTimeStamp("when", Instant.now())
     .addText("winner", "Victor")
     .addSet("fighters", Set.of(UUID.fromString("0193539a-2770-8c09-a32a-111111111111"))));

   List<Object> youPk = result.getInsertedId();
   Map<String, ColumnDefinition> yourPkSchema = result.getPrimaryKeySchema();

   // Leveraging object mapping
   Game match1 = new Game()
     .matchId("mtch_1")
     .round(2)
     .score(20)
     .when(Instant.now())
     .winner("Victor")
     .fighters(Set.of(UUID.fromString("0193539a-2770-8c09-a32a-111111111111")))
     .vector(new DataAPIVector(new float[]{0.4f, -0.6f, 0.2f}));
   db.getTable("games", Game.class).insertOne(match1);
  }
}

To insert a row, define a document object containing key-value pairs of column names and values to insert. Primary key values are required. Any unspecified columns are set to null.

The following example inserts a row with scalar, map, list, and set data. The format of the values for each column depend on the column’s data type.

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 '{
  "insertOne": {
    "document": {
      "string_column": "value",
      "int_column": 2,
      "boolean_column": true,
      "float_column": "NaN",
      "map_column": {
        "key1": "value1",
        "key2": "value2"
      },
      "list_column": [ 10, 11, 12 ],
      "set_column": [ 9, 8, 7 ]
    }
  }
}' | jq

You can insert pre-generated vector data into a vector column as an array or as a binary encoded value. Alternatively, if the column has a vectorize integration, you can automatically generate an embedding from a string.

# Insert vector data as an array
"vector_column": [ 0.1, -0.2, 0.3 ]

# Insert vector data with $binary
"vector_column": { "$binary": "PczMzb5MzM0+mZma" }

# Generate an embedding with vectorize
"vector_column": "Text to vectorize"

For more information, see Vector type.

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 '{
  "insertOne": {
    "document": {
      "name": "Tal Noor",
      "email": "tal@example.com",
      "graduated": true,
      "graduation_year": 2014,
      "grades": {
        "biology_101": 98,
        "math_202": 91
      },
      "extracurriculars": [ "Robotics club", "Cycling team" ],
      "semester_gpas": [ 3.9, 4.0, 3.7 ]
    }
  }
}' | 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