Insert documents (Java)

Inserts multiple documents into a collection.

Documents are stored in collections. They represent a single row or record of data in Astra DB Serverless databases. For more information, see About collections with the Data API (Java).

If the collection is vector-enabled, pregenerated vector embeddings can be included by using the reserved $vector field for each document. If the collection has vectorize enabled, vector embeddings can be automatically generated from text specified in the reserved $vectorize field for each document. You can later use the $vector or $vectorize field to perform a vector search or hybrid search.

If the collection has lexical enabled, use the reserved $lexical field to store a string to index for lexicographical matching and the lexical search component of hybrid search.

Alternatively, you can use the $hybrid shorthand to populate the $vectorize and $lexical fields.

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 documents and returns a wrapper (CollectionInsertManyResult) that includes the IDs of the inserted documents.

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

Parameters

Use the insertMany method, which belongs to the com.datastax.astra.client.Collection class.

Method signature
CollectionInsertManyResult insertMany(
  List<? extends T> documents
)
CollectionInsertManyResult insertMany(
  List<? extends T> documents,
  CollectionInsertManyOptions options
)
Name Type Summary

documents

List<? extends T>

A list of objects describing the documents 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 (Java).

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 (Java).

  • $vector: An optional array of numbers representing a vector embedding for vector search. The $vector field is only supported for vector-enabled collections. A document cannot contain both a $vector and a $vectorize field. For more information, see $vector in collections (Java).

  • $vectorize: An optional string from which to generate vector embeddings for vector search. The $vectorize field is only supported for collections that have an embedding provider integration. A document cannot contain both a $vector and a $vectorize field. For more information, see $vectorize in collections (Java).

  • $lexical: An optional string to make the document searchable for lexicographical matching and the lexical search component of hybrid search. The $lexical field is only supported for collections that have lexical search enabled. For more information, see $lexical in collections (Java).

  • $hybrid: An optional string that populates both $vectorize and $lexical. The $hybrid shorthand is only supported for collections that have vectorize and lexical search enabled. If a document uses $hybrid, it cannot contain a root-level $vectorize or $lexical field. For more information, see $hybrid in collections (Java).

For examples, see Examples.

options

CollectionInsertManyOptions

Optional. The options for this operation. See Methods of the CollectionInsertManyOptions class for more details.

Methods of the CollectionInsertManyOptions class
Name Type Summary

ordered()

boolean

Optional. Whether the insertions must be processed sequentially. If false, the documents may be inserted in an arbitrary order and possibly concurrently. If you don’t need ordered inserts, DataStax recommends setting this parameter to false for faster performance.

concurrency()

int

Optional. The maximum number of concurrent requests to the API at a given time.

If ordered is true, then concurrency must be 1 or unspecified.

For an example, see Insert documents and specify insertion behavior.

Default: 1.

chunkSize()

int

Optional. The number of documents to include in a single API request. DataStax recommends leaving this parameter unspecified to use the system default.

For an example, see Insert documents and specify insertion behavior.

Maximum: 100

Default: 50

timeout

int

Optional. The maximum time, in milliseconds, that the client should wait for each 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.

Examples

The following examples demonstrate how to insert multiple documents into a collection.

Insert documents

The documents can have different structures.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.Arrays;
import java.util.List;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert documents to the collection
    Document document1 = new Document().append("name", "Jane Doe").append("age", 42);
    Document document2 =
        new Document()
            .append("nickname", "Bobby")
            .append("color", "blue")
            .append("foods", Arrays.asList("carrots", "chocolate"));
    CollectionInsertManyResult result = collection.insertMany(List.of(document1, document2));
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Insert documents with vector embeddings

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

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 (Java).

You may also insert a mix of documents with and without the $vector field.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.List;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert documents to the collection
    Document document1 =
        new Document()
            .append("name", "Jane Doe")
            .append("age", 42)
            .append("$vector", new float[] {0.08f, -0.62f, 0.39f});
    Document document2 =
        new Document()
            .append("nickname", "Bobby")
            .append("$vector", new float[] {0.12f, 0.53f, 0.32f});
    CollectionInsertManyResult result = collection.insertMany(List.of(document1, document2));
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Insert documents and generate vector embeddings

Use the reserved $vectorize field to generate a vector embedding automatically. The value of $vectorize can be any string.

The $vectorize field is only supported for collections that have vectorize enabled. For more information, see Create a collection that can automatically generate vector embeddings and $vectorize in collections (Java).

You may also insert a mix of documents with and without the $vectorize field.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.List;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert documents into the collection
    Document document1 =
        new Document()
            .append("name", "Jane Doe")
            .append("age", 42)
            .append("$vectorize", "Text to vectorize for this document");
    Document document2 =
        new Document()
            .append("nickname", "Bobby")
            .append("$vectorize", "Text to vectorize for this document");
    CollectionInsertManyResult result = collection.insertMany(List.of(document1, document2));
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Hybrid search and reranking are 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.

If you plan to use hybrid search to find documents, each document must have both the $lexical field and the $vector field populated.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.documents.Document;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    Document document1 =
        new Document()
            .append("name", "Jane Doe")
            .append("$vector", new float[] {0.08f, -0.62f, 0.39f})
            .append("$lexical", "An author who writes SciFi and fantasy novels.");
    Document document2 =
        new Document()
            .append("name", "Mary Day")
            .append(
                "$vectorize",
                "An athlete who loves biking, hiking, running, and swimming in the outdoors")
            .append("$lexical", "She shares her love of triathlons by coaching kids after school.");
    Document document3 =
        new Document()
            .append("name", "Bobby")
            .append("$hybrid", "A software developer who enjoys managing databases");

    collection.insertMany(document1, document2, document3);
  }
}

Insert documents for retrieval with lexicographical matching

Lexicographical matching 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.

If you plan to use lexicographical matching to find documents, each document must have the $lexical field populated.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.definition.documents.Document;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    Document document1 =
        new Document()
            .append("name", "Jane Doe")
            .append("$lexical", "An author who writes SciFi and fantasy novels.");
    Document document2 =
        new Document()
            .append("name", "Mary Day")
            .append("$lexical", "An active hiker, runner, and triathlete who loves the outdoors.");

    collection.insertMany(document1, document2);
  }
}

Insert documents and specify the IDs

The Java client defines dedicated UUIDv6, UUIDv7, and ObjectId() classes. UUIDs from the Java UUID class are implemented in the UUID v4 standard. ObjectId classes are extracted from the BSON package.

When a unique identifier is retrieved from the server, it is converted to the appropriate class, based on the class definition in the defaultId option for the collection.

To generate new identifiers, you can use methods like new UUIDv6(), new UUIDv7(), or new ObjectId().

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.collections.definition.documents.types.ObjectId;
import com.datastax.astra.client.collections.definition.documents.types.UUIDv7;
import java.util.List;
import java.util.UUID;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert documents to the collection
    Document document1 =
        new Document()
            .append("_id", new ObjectId("6672e1cbd7fabb4e5493916f"))
            .append("name", "Melissa");
    Document document2 = new Document().append("_id", new UUIDv7()).append("name", "Jess");
    Document document3 = new Document().append("_id", UUID.randomUUID()).append("name", "Sam");
    Document document4 = new Document().append("_id", 1).append("name", "Jane");
    Document document5 = new Document().append("_id", "b_023").append("name", "Bobby");
    CollectionInsertManyResult result =
        collection.insertMany(List.of(document1, document2, document3, document4, document5));
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Insert documents and specify insertion behavior

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.options.CollectionInsertManyOptions;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.Arrays;
import java.util.List;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Define the insertion options
    CollectionInsertManyOptions options =
        new CollectionInsertManyOptions().chunkSize(20).concurrency(3).ordered(false).timeout(1000);

    // Insert documents into the collection
    Document document1 = new Document().append("name", "Jane Doe").append("age", 42);
    Document document2 =
        new Document()
            .append("nickname", "Bobby")
            .append("color", "blue")
            .append("foods", Arrays.asList("carrots", "chocolate"));
    CollectionInsertManyResult result =
        collection.insertMany(List.of(document1, document2), options);
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Insert documents with a binary field

You can insert binary data as a byte array with $binary.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.List;
import java.util.Map;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert a document with a binary field
    byte[] exampleBytes = {
      (byte) 0x3D, (byte) 0xFB, (byte) 0xE7, (byte) 0x6D,
      (byte) 0x3E, (byte) 0xE9, (byte) 0x78, (byte) 0xD5,
      (byte) 0x3F, (byte) 0x49, (byte) 0xFB, (byte) 0xE7
    };

    Document document = new Document().append("exampleBinary", Map.of("$binary", exampleBytes));

    CollectionInsertManyResult result = collection.insertMany(List.of(document));

    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

Insert documents 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.

import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertManyResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import java.util.List;
import java.util.Map;

public class Example {

  public static void main(String[] args) {
    // Get an existing collection
    Collection<Document> collection =
        new DataAPIClient("APPLICATION_TOKEN")
            .getDatabase("API_ENDPOINT")
            .getCollection("COLLECTION_NAME");

    // Insert documents into the collection
    Document document1 =
        new Document()
            .append("title", "Hidden Shadows of the Past")
            .append("genres", List.of("Biography", "Graphic Novel", "Dystopian", "Drama"))
            .append(
                "metadata",
                Map.of(
                    "isbn", "978-1-905585-40-3",
                    "language", "French",
                    "edition", "Anniversary Edition"));
    Document document2 =
        new Document()
            .append("title", "Bake a Dozen")
            .append("genres", List.of("Biography", "Fiction"))
            .append(
                "metadata",
                Map.of(
                    "isbn", "342-2-875587-50-2",
                    "language", "English",
                    "edition", "Illustrated Edition"));
    CollectionInsertManyResult result = collection.insertMany(List.of(document1, document2));
    System.out.println("IDs inserted: " + result.getInsertedIds());
  }
}

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