Insert a document (Java)
Inserts a single document 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.
If the collection has vectorize enabled, vector embeddings can be automatically generated from text specified in the reserved $vectorize field.
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 document and returns a wrapper (CollectionInsertOneResult) that includes the ID of the inserted document.
The ID value depends on the ID type. For more information, see Document IDs (Java).
Parameters
Use the insertOne method, which belongs to the com.datastax.astra.client.Collection class.
Method signature
CollectionInsertOneResult insertOne(
T document
)
CollectionInsertOneResult insertOne(
T document,
CollectionInsertOneOptions options
)
| Name | Type | Summary |
|---|---|---|
|
|
An object 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:
Reserved fields are tied to specific functionality. Include the following reserved fields in your documents, if applicable:
For examples, see Examples. |
|
Optional. The options to apply to the insert operation. |
Examples
The following examples demonstrate how to insert a document into a collection.
Insert a document
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
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 into the collection
Document document =
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"))
.append("number_of_pages", 245);
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
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 (Java).
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
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");
// Insert a document into the collection
Document document =
new Document()
.append("name", "Jane Doe")
.append("$vector", new float[] {0.08f, -0.62f, 0.39f});
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
Insert a document and generate vector embeddings
Use the reserved $vectorize field to generate a vector embedding automatically. The value of $vectorize can be any string.
You can later use this field to perform a vector search.
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).
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
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");
// Insert a document into the collection
Document document =
new Document().append("name", "Jane Doe").append("$vectorize", "Text to vectorize");
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
Insert a document for retrieval with hybrid search
|
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 this document, the document must have both the $lexical field and the $vector field populated.
Example specifying the $vector and $lexical fields:
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 document =
new Document()
.append("name", "Jane Doe")
.append("$vector", new float[] {0.08f, -0.62f, 0.39f})
.append(
"$lexical",
"An athlete who loves biking, hiking, running, and swimming in the outdoors");
collection.insertOne(document);
}
}
Example specifying the $vectorize and $lexical fields:
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 document =
new Document()
.append("name", "Jane Doe")
.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");
collection.insertOne(document);
}
}
Example using the $hybrid shorthand, which populates the $lexical and $vectorize field:
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 document =
new Document()
.append("name", "Jane Doe")
.append(
"$hybrid",
"An athlete who loves biking, hiking, running, and swimming in the outdoors");
collection.insertOne(document);
}
}
Insert a document 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 this document, the 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 document =
new Document()
.append("name", "Jane Doe")
.append("$vector", new float[] {0.08f, -0.62f, 0.39f})
.append(
"$lexical",
"An athlete who loves biking, hiking, running, and swimming in the outdoors");
collection.insertOne(document);
}
}
Insert a document and specify the ID
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().
Example using new UUIDv7(), if the collection has UUIDv7 set as its default ID:
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
import com.datastax.astra.client.collections.definition.documents.Document;
import com.datastax.astra.client.collections.definition.documents.types.UUIDv7;
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 into the collection
Document document = new Document().id(new UUIDv7()).append("name", "Jane Doe");
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
Example specifying the ID without UUID or ObjectId:
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
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");
// Insert a document into the collection
Document document = new Document().id(1).append("name", "Jane Doe");
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
Insert a document 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.CollectionInsertOneResult;
import com.datastax.astra.client.collections.definition.documents.Document;
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));
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
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.
import com.datastax.astra.client.DataAPIClient;
import com.datastax.astra.client.collections.Collection;
import com.datastax.astra.client.collections.commands.results.CollectionInsertOneResult;
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 into the collection
Document document =
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"));
CollectionInsertOneResult result = collection.insertOne(document);
System.out.println(result.getInsertedId());
}
}
Client reference
For more information, see the client reference.