Skip to content

Repository files navigation

Java Client for Data API

License Apache2Maven CentraljavadocDocumentation

A Java client for DataStax Astra DB.

This client library provides a simplified way to interact with the Data API for Astra DB Serverless, Hyper-Converged Database (HCD), or local instances.

Key Features

  • 🚀 Zero-config: Connect to Astra DB in 3 lines of code.
  • 🔍 Unified API: Seamless support for Collections (JSON Documents) and Tables (Structured Rows).
  • 🧠 AI-Ready: Native support for Vector Search and Server-side Embeddings (Vectorize).
  • Java-Centric: Fluent builders, POJO mapping, and Jackson support.
  • Sync & Async: Built on HttpClient with full support for synchronous and asynchronous operations.

Table of Contents

  1. Quickstart
  2. Architecture Overview
  3. Connecting to a Database
  4. Collections and Documents
  5. Tables and POJO Mapping
  6. Support Functions
  7. Samples
  8. Running Tests
  9. Help & Support
  10. Resources & Documentation

1. Quickstart

Prerequisites

Installation

Maven

<dependency>
<groupId>com.datastax.astra</groupId>
<artifactId>astra-db-java</artifactId>
<version>2.1.7</version>
</dependency>

Gradle

implementation 'com.datastax.astra:astra-db-java:2.1.7'

⚡ Connect and Query in 30 Seconds

Click to view required imports
importcom.datastax.astra.client.DataAPIClient;
importcom.datastax.astra.client.databases.Database;
importcom.datastax.astra.client.collections.Collection;
importcom.datastax.astra.client.collections.definition.CollectionDefinition;
importcom.datastax.astra.client.collections.definition.documents.Document;
importcom.datastax.astra.client.core.vector.SimilarityMetric;
importcom.datastax.astra.client.core.query.Sort;
importcom.datastax.astra.client.core.query.FindOptions;
importjava.util.List;
importjava.util.UUID;
publicclassQuickstart {
publicstaticvoidmain(String[] args) {
// 1. ConnectDataAPIClientclient = newDataAPIClient("AstraCS:...");
Databasedb = client.getDatabase("[https://01234567-....apps.astra.datastax.com](https://01234567-....apps.astra.datastax.com)");
// 2. Create a vector collectionCollection<Document> collection = db.createCollection(
"dreams",
CollectionDefinition.builder()
.vector(3, SimilarityMetric.COSINE)
.build()
);
// 3. Insert documents with vectorscollection.insertMany(List.of(
newDocument()
.id(UUID.fromString("018e65c9-e33d-749b-9386-e848739582f0"))
.append("summary", "Riding the waves")
.append("tags", List.of("sport"))
.vector(newfloat[]{0f, 0.2f, 1f}),
newDocument()
.append("summary", "Friendly aliens in town")
.append("tags", List.of("scifi"))
.vector(newfloat[]{-0.3f, 0f, 0.8f})
));
// 4. Vector searchList<Document> results = collection.find(
newDocument(),
newFindOptions()
.sort(Sort.vector(newfloat[]{0f, 0.2f, 0.4f}))
.limit(2)
.includeSimilarity(true)
).toList();
results.forEach(doc ->
System.out.println(doc.getString("summary") + ": " + doc.getSimilarity())
);
}
}

2. Architecture Overview

The SDK follows a layered hierarchy that mirrors the Data API itself.

graph TD
A[DataAPIClient] -->|connects to| B[Database]
A -->|manages| F[AstraDBAdmin]
B -->|contains| C[Collection&lt;T&gt;]
B -->|contains| D[Table&lt;T&gt;]
F -->|manages| G[DatabaseAdmin]
C -->|CRUD + Search| E["insert · find · update · delete"]
D -->|CRUD + Search| E
style A fill:#1a1a2e,stroke:#e94560,color:#fff
style B fill:#16213e,stroke:#0f3460,color:#fff
style C fill:#0f3460,stroke:#533483,color:#fff
style D fill:#0f3460,stroke:#533483,color:#fff
style F fill:#16213e,stroke:#0f3460,color:#fff
style G fill:#0f3460,stroke:#533483,color:#fff
Loading
LayerPurpose
ClientEntry point. Holds authentication token and HTTP configuration.
DatabaseRepresents a single database/keyspace. Creates and retrieves collections and tables.
CollectionDocument-oriented operations on schemaless JSON data (MongoDB-style).
TableRow-oriented operations on structured, schema-defined data.

3. Connecting to a Database

3.1 Astra DB Serverless

importcom.datastax.astra.client.DataAPIClient;
importcom.datastax.astra.client.databases.Database;
// Connect with your Astra tokenDataAPIClientclient = newDataAPIClient("AstraCS:...");
Databasedatabase = client.getDatabase("[https://01234567-....apps.astra.datastax.com](https://01234567-....apps.astra.datastax.com)");

3.2 HCD and Local Installations

Connect to a Hyper-Converged Database (HCD), local DSE, or any Data API-compatible instance using a UsernamePasswordTokenProvider.

importcom.datastax.astra.client.DataAPIClient;
importcom.datastax.astra.client.core.auth.UsernamePasswordTokenProvider;
TokenProvidertp = newUsernamePasswordTokenProvider("cassandra", "cassandra");
DataAPIClientclient = newDataAPIClient(tp);
Databasedatabase = client.getDatabase("http://localhost:8181");

Tip: Start a local HCD instance with docker-compose up -d using the docker-compose.yml included in this repository.


4. Collections and Documents

4.1 Working with Collections

Server-Side Embeddings (Vectorize)

Delegate embedding computation to the server by specifying a provider (e.g., OpenAI, NVIDIA, HuggingFace) at collection creation.

Collection<Document> collection = database.createCollection(
"my_vectorize_collection",
CollectionDefinition.builder()
.vectorize("openai", "text-embedding-3-small")
.build()
);
// Insert — the server generates the embedding automaticallycollection.insertOne(newDocument().append("$vectorize", "A text passage to embed"));
// Search using natural languageList<Document> results = collection.find(
newFindOptions().sort(Sort.vectorize("search query"))
).toList();

Filtering and Updates

importcom.datastax.astra.client.core.query.Filter;
// Find with a filterList<Document> scifiDocs = collection.find(
newFilter().where("tags", "scifi")
).toList();
// Update a documentcollection.updateOne(
newFilter().where("tags", "sport"),
newDocument().append("$set", newDocument().append("summary", "Surfers' paradise"))
);

4.2 Working with Documents

The Document class is the primary data container for collections.

📖 Deep Dive: See the Document API Reference for full details on escaping rules, dot-notation access, and typed getters.


5. Tables and POJO Mapping

5.1 Working with Tables

Tables provide structured, schema-defined storage with full vector search support.

// Define the schemaTableDefinitiontableDef = TableDefinition.builder()
.addColumn("dream_id", ColumnTypes.INT)
.addColumn("summary", ColumnTypes.TEXT)
.addVectorColumn("dream_vector", 3, SimilarityMetric.COSINE)
.addPartitionBy("dream_id")
.build();
TablemyTable = database.createTable("dreams_table", tableDef);
// Insert rowsmyTable.insertOne(
newRow()
.add("dream_id", 103)
.add("summary", "Riding the waves")
.add("dream_vector", newfloat[]{0f, 0.2f, 1f})
);

5.2 POJO Mapping (Object Mapping)

Map collections and tables directly to Java classes using Jackson annotations.

publicclassDream {
@JsonProperty("_id")
privateintdreamId;
@JsonProperty("$vector")
privatefloat[] vector;
// ... getters/setters
}
// Get a typed collectionCollection<Dream> dreams = database.getCollection("dreams_collection", Dream.class);
dreams.insertOne(newDream(500, ...));

6. Support Functions

  • Administration: Use client.getAdmin() to manage databases and database.getDatabaseAdmin() to manage keyspaces.
  • Logging: The client uses SLF4J. Configure Logback or Log4j2 to see debug logs.
  • Error Handling: Catch DataAPIFaultyResponseException for API errors and DataAPIHttpException for network issues.

7. Samples

The astra-db-java-samples module contains runnable examples covering the main SDK features. Each sample is a standalone main() class you can run after setting your credentials.

Full index and tutorials: see the samples README for step-by-step tutorials and the complete list of samples.

CategorySampleDescription
QuickstartSampleQuickstartHCDEnd-to-end HCD quickstart: connect, create keyspace, vectorize query
ClientSampleClientConfigurationFull configuration cookbook: HTTP settings, timeouts, proxies, observers
CollectionsSampleCollectionInsertManyBulk insert with chunk size, concurrency, and ordering options
SampleCollectionVectorizeServer-side embeddings (vectorize) for insert and search
SampleCollectionDatesWorking with Calendar, Date, and Instant fields
SampleDocumentIdsAll supported _id types: UUID, UUIDv6/v7, ObjectId, etc.
SampleHybridCollectionDefinitionHybrid collection with vector, lexical, and reranking
SampleFindAndRerankHybrid search with findAndRerank API
TablesSampleTableRowsTyped row builders and POJO mapping with @Column
SampleTableVectorizeVectorize on table columns with similarity search
SampleTableUdtObjectMappingUser-Defined Types (UDT) with nested POJO mapping

8. Running Tests and Contributing

We welcome contributions!

For details on running the test suite (Local, Dev, Prod), configuring environment variables, and our coding standards, please see CONTRIBUTING.md.


9. Help & Support

If you encounter any issues or have questions:

  • 🐛 Report Bugs: Open an issue on GitHub Issues.
  • 💬 Community: Join the discussion on the DataStax Discord.
  • 📚 StackOverflow: Tag questions with astra-db.

10. Resources & Documentation

Astra DB Serverless

Hyper-Converged Database (HCD)


Copyright © 2024 DataStax. Distributed under the Apache License 2.0.

Releases

Packages

Used by

Contributors

Languages