Insert rows (Python)
|
Tables with the Data API are currently in public preview. Development is ongoing, and the features and functionality are subject to change. Hyper-Converged Database (HCD), and the use of such, is subject to the DataStax Preview Terms. |
Inserts multiple rows 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 type compatibility in tables (Python).
For general information about working with tables and rows, see About tables with the Data API (Python).
|
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
Inserts the specified rows and returns a TableInsertManyResult object that includes the primary key of the inserted rows as dictionaries and as ordered tuples.
If a row with the specified primary key already exists in the table, the row is overwritten with the specified column values. Unspecified columns remain unchanged.
If a row fails to insert and the insertions are sequential (ordered is True), then that row and all subsequent rows are not inserted.
The resulting error message indicates the first row that failed to insert.
If a row fails to insert and the insertions are not sequential (ordered is False), the operation will try to insert the remaining rows and then throw an error.
The error indicates which rows were successfully inserted and the problems with the failed rows.
Example response:
TableInsertManyResult(
inserted_ids=[
{'match_id': 'fight4', 'round': 1},
{'match_id': 'fight5', 'round': 1},
{'match_id': 'fight5', 'round': 2},
{'match_id': 'fight5', 'round': 3},
{'match_id': 'challenge6', 'round': 1}
... (13 total)
],
inserted_id_tuples=[
('fight4', 1), ('fight5', 1), ('fight5', 2),
('fight5', 3), ('challenge6', 1) ... (13 total)
],
raw_results=...
)
Parameters
Use the insert_many method, which belongs to the astrapy.Table class.
Method signature
insert_many(
rows: Iterable[Dict[str, Any]],
*,
ordered: bool,
chunk_size: int,
concurrency: int
general_method_timeout_ms: int,
request_timeout_ms: int,
timeout_ms: int,
) -> TableInsertManyResult
| Name | Type | Summary |
|---|---|---|
|
|
An iterable of dictionaries, where each dictionary defines a row to insert. All primary key values are required. To reduce tombstones, you should not explicitly set a column to The table definition determines the columns in the row, the type for each column, and the primary key. To get this information, see List table metadata (Python). |
|
|
Whether to insert the rows sequentially. If false, the rows are inserted in an arbitrary order with possible concurrency. This results in a much higher insert throughput than an equivalent ordered insertion. Default: false |
|
|
The maximum number of concurrent requests to the API at a given time. For ordered insertions, must be 1 or unspecified. Default: |
|
|
The number of rows to insert in a single API request. DataStax recommends that you leave this unspecified to use the system default. |
|
|
Optional. The maximum time, in milliseconds, that the whole operation, which might involve multiple HTTP requests, can take. This parameter is aliased as Default: The default value for the table. This default is 30 seconds unless you specified a different default when you initialized the |
|
|
Optional. The maximum time, in milliseconds, that the client should wait for each underlying HTTP request. Default: The default value for the table. This default is 30 seconds unless you specified a different default when you initialized the |
Examples
The following examples demonstrate how to insert multiple rows into a table.
Insert rows
When you insert rows, you must specify a non-null value for each primary key column for each row.
Non-primary key columns are optional.
To reduce tombstones, you should not explicitly set a column to null.
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.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIDate, DataAPISet
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")
# Insert rows into the table
result = table.insert_many(
[
{
"title": "Computed Wilderness",
"author": "Ryan Eau",
"number_of_pages": 432,
"due_date": DataAPIDate.from_string("2024-12-18"),
"genres": DataAPISet(["History", "Biography"]),
},
{
"title": "Desert Peace",
"author": "Walter Dray",
"number_of_pages": 355,
"rating": 4.5,
},
]
)
Insert rows with vector embeddings
You can only insert vector embeddings into vector columns.
To create a table with a vector column, see Create a table (Python). To add a vector column to an existing table, see Alter a table (Python).
All embeddings in the column should use the same provider, model, and dimensions. Mismatched embeddings can cause inaccurate vector searches.
You can use the astrapy.data_types.DataAPIVector class to binary-encode your vector embeddings.
DataStax recommends that you always use a DataAPIVector object instead of a list of floats to improve performance.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIVector
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")
# Insert rows into the table
result = table.insert_many(
[
{
"title": "Computed Wilderness",
"author": "Ryan Eau",
"summary_genres_vector": DataAPIVector([0.08, -0.62, 0.39]),
},
{
"title": "Desert Peace",
"author": "Walter Dray",
"summary_genres_vector": DataAPIVector([0.12, 0.53, 0.32]),
},
]
)
Insert rows and specify insertion behavior
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.
from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.data_types import DataAPIDate, DataAPISet
# Get an existing table
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
"API_ENDPOINT",
token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
keyspace="KEYSPACE_NAME",
)
table = database.get_table("TABLE_NAME")
# Insert rows into the table
result = table.insert_many(
[
{
"title": "Computed Wilderness",
"author": "Ryan Eau",
"number_of_pages": 432,
"due_date": DataAPIDate.from_string("2024-12-18"),
"genres": DataAPISet(["History", "Biography"]),
},
{
"title": "Desert Peace",
"author": "Walter Dray",
"number_of_pages": 355,
"rating": 4.5,
},
],
chunk_size=2,
concurrency=2,
ordered=False,
)
Client reference
For more information, see the client reference.