Insert a document (Python)

Inserts a single document into a collection.

Documents are stored in collections. They represent a single row or record of data in Hyper-Converged Database (HCD) databases. For more information, see About collections with the Data API (Python).

If the collection is vector-enabled, pregenerated vector embeddings can be included by using the reserved $vector field. You can later use the $vector field to perform a vector search.

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 document and returns a CollectionInsertOneResult object that includes the ID of the inserted document and details about the operation.

The ID value depends on the ID type. For more information, see Document IDs (Python).

Example response:

CollectionInsertOneResult(inserted_id='92b3c4f4-db44-4440-b4c4-f4db54e440b8', raw_results=...)

Parameters

Use the insert_one method, which belongs to the astrapy.Collection class.

Method signature
insert_one(
  document: Dict[str, Any],
  *,
  general_method_timeout_ms: int,
  request_timeout_ms: int,
  timeout_ms: int,
) -> CollectionInsertOneResult
Name Type Summary

document

Dict[str, Any]

A dictionary describing the document to insert.

A document can contain user-defined and reserved fields.

User-defined field names can be any non-empty sequence of Unicode characters, with the following exceptions:

  • Field names cannot start with $.

  • Field names cannot be exactly *.

  • If a field name includes & or ., you must escape those characters when you use the field in a filter, sort, projection, or update. For more information, see Work with . and & in field names (Python).

Reserved fields are tied to specific functionality. Include the following reserved fields in your documents, if applicable:

  • _id: An optional unique identifier for the document. If _id is omitted, it is created automatically based on the collection’s ID type. For more information, see Document IDs (Python).

  • $vector: An optional array of numbers representing a vector embedding for vector search. The $vector field is only supported for vector-enabled collections.

For examples, see Examples.

general_method_timeout_ms

int

Optional. The maximum time, in milliseconds, that the client should wait for the underlying HTTP request.

Default: The default value for the collection. This default is 30 seconds unless you specified a different default when you initialized the Collection or DataAPIClient object. For more information, see Timeout options.

request_timeout_ms

int

Optional. An alias for general_method_timeout_ms. Since this method issues a single HTTP request, general_method_timeout_ms and request_timeout_ms are equivalent.

timeout_ms

int

Optional. An alias for general_method_timeout_ms.

Examples

The following examples demonstrate how to insert a document into a collection.

Insert a document

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

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "title": "Hidden Shadows of the Past",
        "genres": ["Biography", "Graphic Novel", "Dystopian", "Drama"],
        "metadata": {
            "isbn": "978-1-905585-40-3",
            "language": "French",
            "edition": "Anniversary Edition",
        },
        "number_of_pages": 245,
    }
)

Insert a document with vector embeddings

Use the reserved $vector field to insert a document with pregenerated vector embeddings.

You can later use this field to perform a vector search.

All embeddings in the collection should use the same provider, model, and dimensions. Mismatched embeddings can cause inaccurate vector searches.

The $vector field is only supported for vector-enabled collections. For more information, see Create a collection that can store vector embeddings and $vector in collections (Python).

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

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "name": "Jane Doe",
        "$vector": [0.08, -0.62, 0.39],
    }
)

Insert a document and specify the ID

The Python client provides the UUID and ObjectId classes to use and generate identifiers.

Example using UUID:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.ids import UUID

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "_id": UUID("1ef2e42c-1fdb-6ad6-aae4-e84679831739"),
        "name": "Jane Doe",
    }
)

Example using ObjectId:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment
from astrapy.ids import ObjectId

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "_id": ObjectId("6672e1cbd7fabb4e5493916f"),
        "name": "Jane Doe",
    }
)

Example specifying the ID without UUID or ObjectId:

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "_id": 1,
        "name": "Jane Doe",
    }
)

Insert a document with a binary field

You can insert binary data as a Base64-encoded string with $binary or as a bytes value.

The Python client returns binary data received from the Data API as a bytes value, even if it was inserted as a Base64-encoded string.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document with binary fields
result = collection.insert_one(
    {
        "exampleBinary": {"$binary": "PfvnbT7peNU/Sfvn"},
        "anotherExampleBinary": b"=\xfb\xe7m>\xe9x\xd5?I\xfb\xe7",
    }
)

Insert a document with nested fields

Although you can use dot notation in a filter to find a document, you cannot use dot notation to insert a document. To specify nested fields in the inserted document, you must build a map, list, or set.

from astrapy import DataAPIClient
from astrapy.authentication import UsernamePasswordTokenProvider
from astrapy.constants import Environment

# Get an existing collection
client = DataAPIClient(environment=Environment.HCD)
database = client.get_database(
    "API_ENDPOINT",
    token=UsernamePasswordTokenProvider("USERNAME", "PASSWORD"),
    keyspace="KEYSPACE_NAME",
)
collection = database.get_collection("COLLECTION_NAME")

# Insert a document into the collection
result = collection.insert_one(
    {
        "title": "Hidden Shadows of the Past",
        "genres": ["Biography", "Graphic Novel", "Dystopian", "Drama"],
        "metadata": {
            "isbn": "978-1-905585-40-3",
            "language": "French",
            "edition": "Anniversary Edition",
        },
    }
)

Client reference

For more information, see the client reference.

Was this helpful?

Give Feedback

How can we improve the documentation?

© Copyright IBM Corporation 2026 | 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: Contact IBM