Skip to content

• Java


Astra offers different Apis. Select the API you want to use below to get documentation.

              

1. Pre-requisites

Setup your JAVA Development environment
  • Install Java Development Kit (JDK) 8+

Use java reference documentation targetting your operating system to install a Java Development Kit. You can then validate your installation with the following command.

java --version
  • Install Apache Maven (3.8+)

Samples and tutorials have been designed with Apache Maven. Use the reference documentation top install maven validate your installation with

mvn -version
Setup Datastax Astra DB
  • Create your DataStax Astra account:

Sign Up

  • Create an Astra Token

An astra token acts as your credentials, it holds the different permissions. The scope of a token is the whole organization (tenant) but permissions can be edited to limit usage to a single database.

To create a token, please follow this guide

The Token is in fact three separate strings: a Client ID, a Client Secret and the token proper. You will need some of these strings to access the database, depending on the type of access you plan. Although the Client ID, strictly speaking, is not a secret, you should regard this whole object as a secret and make sure not to share it inadvertently (e.g. committing it to a Git repository) as it grants access to your databases.

{
  "ClientId": "ROkiiDZdvPOvHRSgoZtyAapp",
  "ClientSecret": "fakedfaked",
  "Token":"AstraCS:fake"
}

It is handy to have your token declare as an environment variable (replace with proper value):

export ASTRA_TOKEN="AstraCS:replace_me"
  • Create a Database and a keyspace

With your account you can run multiple databases, a Databases is an Apache Cassandra cluster. It can live in one or multiple regions (dc). In each Database you can have multiple keyspaces. In the page we will use the database name db_demo and the keyspace keyspace_demo.

You can create the DB using the user interface and here is a tutorial. You can also use Astra command line interface. To install and setup the CLI run the following:

curl -Ls "https://dtsx.io/get-astra-cli" | bash
source ~/.astra/cli/astra-init.sh
astra setup --token ${ASTRA_TOKEN}

To create DB and keyspace with the CLI:

astra db create db_demo -k keyspace_demo --if-not-exists
  • Download the Secure Connect Bundle for current database

A Secure Connect Bundle contains the certificates and endpoints informations to open a mTLS connection. Often mentionned as scb its scope is a database AND a region. If your database is deployed on multiple regions you will have to download the bundle for each one and initiate the connection accordingly. Instructions to download Secure Connect Bundle are here

You can download the secure connect bundle from the user interface and here is a tutorial. You can also use Astra command line interface.

astra db download-scb db_demo -f /tmp/secure-connect-bundle-db-demo.zip

2. Cassandra Drivers

2.1 Drivers 4.x

The official documentation for Cassandra drivers is available on datastax documentation portal

4.x is the recommended version of the cassandra drivers.

Quickstart

Project Setup
  • Any version 4.x should be compatible with Astra.

  • Update your pom.xml file with the latest version of the 4.x libraries Maven Central

<!-- (REQUIRED) -->
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-core</artifactId>
<version>${latest4x}</version>
</dependency>

<!-- OPTIONAL -->
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-query-builder</artifactId>
<version>${latest4x}</version>
</dependency>
<dependency>
<groupId>com.datastax.oss</groupId>
<artifactId>java-driver-mapper-runtime</artifactId>
<version>${latest4x}</version>
</dependency>
Sample Code
AstraDriver4x.java
package com.datastax.astra;
import java.nio.file.Paths;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraDriver4x {
  public static void main(String[] args) {
    try (CqlSession cqlSession = CqlSession.builder()
      .withCloudSecureConnectBundle(Paths.get("/tmp/secure-connect-bundle-db-demo."))
      .withAuthCredentials("client_id","client_secret")
      .withKeyspace("keyspace_demo")
      .build()) {
       System.out.println("Connected to " + cqlSession.getKeyspace().get());
    }
  }
}

 Download The project

What you need to know

📦 About Secure Connect Bundle

  • The path to the secure connect bundle for your Astra database is specified with withCloudSecureConnectBundle(), it accepts String, File and URL.
  • An SSL connection will be established automatically. Manual SSL configuration is not allowed, any settings in the driver configuration (advanced.ssl-engine-factory) will be ignored.
  • The secure connect bundle contains all of the necessary contact information. Specifying contact points manually is not allowed, and will result in an error

⚙️ About Parameters

  • The authentication credentials must be specified separately with withAuthCredentials(), and match the username and password that were configured when creating the Astra database.

  • Another pair is accepted for the credentials: token for the username and the value of the token starting by AstraCS:... is accepted

// Initialization with a token and not pair clientId/slientSecret
CqlSession.builder().withAuthCredentials("token","AstraCS:....")
  • The keyspace is here required and provided with .withKeyspace()

  • if the driver configuration does not specify an explicit consistency level, it will default to LOCAL_QUORUM (instead of LOCAL_ONE when connecting to a normal Cassandra database).

  • Extra configuration can be provided in application.conf file.

🔌 About CqlSession

  • All operations of the drivers can be execute from this object.

  • It a stateful, autocloseable, object, and must be a singleton in your application.

File-based configuration

Alternatively, or complementary the connection information can be specified in the driver’s configuration file (application.conf). Merge the following options with any content already present. All keys available in the file are available in reference.conf

Recommended application.conf
datastax-java-driver {
  basic {
    request {
        timeout     = 10 seconds
      consistency = LOCAL_QUORUM
    }
    # change this to match the target keyspace
    session-keyspace = keyspace_name
    cloud {
      secure-connect-bundle = /path/to/secure-connect-database_name.zip
    }
  }
  advanced {
    auth-provider {
      class = PlainTextAuthProvider
      username = user_name 
      password = password
    }
    connection {
      init-query-timeout = 10 seconds
      set-keyspace-timeout = 10 seconds
      pool {
        local-size = 1
      }
    }
    reconnection-policy {
      class = ExponentialReconnectionPolicy
      base-delay = 5 seconds
      max-delay = 60 seconds
    }
    control-connection.timeout = 10 seconds
  }
}

With the file in the classpath, the previous code is updated as the following:

import java.nio.file.Paths;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraDriver4x {
  public static void main(String[] args) {
    try (CqlSession cqlSession = CqlSession.builder().build()) {
      System.out.println("Hello keyspace {} !" + cqlSession.getKeyspace().get());
    }
  }
}
What you need to know
  • The configuration file application.conf is automatically loaded when present on the classpath. It can be used in any java-based application with no difference (spring, quarkus...)
  • dc-failover is NOT available as a different secure connect bundles are required for different regions (1 region = 1 dc in Astra)

Sample Code Library

Classname Description
ShowMetaData4x Connect to Astra and show keyspaces and metadata from the CqlSession
CreateSchema4x Create schema with different table and type (UDT) if they do not exist in keyspace
DropSchema4x Remove assets of the schema,table and type (UDT) if they exist in target keyspace
ConfigurationFile4x Setup the driver to use customize configuration file and not default application.conf
ProgrammaticConfiguration Setup the driver in a programmatic way and not reading application.conf
Getting Started First touch with executing queries
Simple4x Read, update, insert, delete operations using QueryBuilder
Paging4x Illustrating FetchSize and how to retrieve page by page
Batches4x Group statements within batches
ListSetMapUdt4x Advanced types insertions with list, set, map but also User Defined Type
Json4x Work with columns or full record with JSON
Async4x Sample operations as Simple in Asynchronous way
ObjectMapping4x Map table record to Java POJO at driver level
Counter4x Working with counters increment/decrement
Lwt4x Working for Lightweight transactions read-before-write
BlobAndCodec4x Working with BLOB and binary data but also how to create your own CustomCodec
CloudAstra4x Working with BLOB and binary data but also how to create your own CustomCodec
Reactive4x Working with the Reactive API introduce in driver 4.x
Classname Description
Spring PetClinic in Reactive Implementation of the PetClinic spring application using the reactive part of the drivers. Other frameworks used are spring-data-cassandra and spring-boot
Quarkus Todo application Leveraging Quarkus extension to build a quarkus application
Better Reads A clone of Good reads using Spring Boot and Spring Data Cassandra
E-Commerce A full fledge e-commerce portal with catalog, shopping cart, payment and order processing with Spring Boot
Build Microservices Microservices with Spring
Devoxx 2022 3h of deep dive on how to build java applications with Spring, Quarkus and Micronaut
Java Native Build todo application in Java Native with Spring, Quarkus and Micronaut
Stargate TV Show Reproduce the wheel for Stargate TV Show with destinations saved in Astra
Spring Data Cassandra Deep dive with Spring data cassandra

2.2 Drivers 3.x

The official documentation for the drivers can be found here

Version 3.x is still maintained but not recommended version. It will not get evolutions in the future"

QuickStart

Project Setup
  • Version 3.8+ or more is required to connect to Astra.

  • Update your pom.xml file with the latest version of the 3.x libraries: Maven Central

<!-- Mandatory -->
<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-core</artifactId>
 <version>${latest3x}</version> 
</dependency>

<!-- Optional, Used for object mapping-->
<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-mapping</artifactId>
  <version>${latest3x}</version> 
</dependency>
<!-- Optional, Used for conversion ad-hoc-->
<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-extra</artifactId>
  <version>${latest3x}</version> 
</dependency>
Sample Code
AstraDriver3x.java
package com.datastax.astra;

import java.io.File;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public class AstraDriver3x {
  public static void main(String[] args) {
    try(Cluster cluster = Cluster.builder()
     .withCloudSecureConnectBundle(new File("/tmp/scb.zip"))
     .withCredentials("client_id", "client_secret")
     .build()) {

       try(Session session = cluster.connect("demo_keyspace")) {
         System.out.println(session.getLoggedKeyspace());
       }
    }
  }
}

 Download Project

What you need to know
  • If you work with previous versions of the driver (lower than 3.8 ) the support of Astra is not Ad-hoc it is recommended to migrate. Yet it is possible to use the SSL options. Documentation and sample codes can be found here.

Sample Code Library

Classname Description
GettingStarted3x First touch with executing queries
Simple3x Read, update, insert, delete operations using QueryBuilder
ShowMetaData3x Connect to cluster then show keyspaces and metadata
CreateKeyspace3x Create the killrvideo keyspace using SchemaBuilder if not exist
CreateSchema3x Create table and type in killrvideo keyspace if they don't exist
DropKeyspace3x Drop the killrvideo keyspace if existis using SchemaBuilder
DropSchema3x Drop all table and type in killrvideo keyspace if they exist
Paging3x Illustrating FetchSize and how to retrieve page by page
Batches3x Group statements within batches
ListSetMapUdt3x Advanced types insertions with list, set, map but also User Defined Type
Json3x Work with columns or full record with JSON
Async3x Sample operations as Simple in Asynchronous way
ObjectMapping3x Map table record to Java POJO at driver level
Counter3x Working with counters increment/decrement
Lwt3x Working for Lightweight transactions read-before-write
BlobAndCodec3x Working with BLOB and binary data but also how to create your own CustomCodec
CloudAstra3x Working with BLOB and binary data but also how to create your own CustomCodec

2.3 Astra SDK

The Astra Software Deployment Kit, or SDK, allows developers to connect to Astra with all the different interfaces available. In this section we will detailed how to setup this client library to use the cassandra drivers interface.

Quickstart

Project Setup
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import com.datastax.oss.driver.api.core.CqlSession;

public class AstraSdkDrivers {
    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .withCqlKeyspace("demo")
                .enableCql()
                .build()) {

            try(CqlSession cqlSession = astraClient.cqlSession()) {
                System.out.println("+ Cql Version (cql)   : " + cqlSession
                  .execute("SELECT cql_version from system.local")
                  .one().getString("cql_version"));
            }
        }
    }
}

 Download Project

What you need to know

🔑 About Credentials

  • The pair clientId/ clientSecret hold your credentials. It can be replaced by the value of the token only.
AstraClient.builder().withToken("AstraCS:...");
  • There is no need to download the cloud securebundle in advance as it will be downloaded for you in folder ~.astra/scb by default. Stil, but you can also provide the file location with .withCqlCloudSecureConnectBundle():
AstraClient.builder().withCqlCloudSecureConnectBundle("/tmp/scb.zio");
  • Notice than enableCQL() must be explictely provided. The sdk will open only the asked interfaces in order to limit the resource consumption.

⚙️ About Database identifiers

  • databaseId/databaseRegion will be required to locate the proper endpoint. You can find them for a particular database with either the cli.
$astra db list

+---------------------+--------------------------------------+---------------------+-----------+
| Name                | id                                   | Default Region      | Status    |
+---------------------+--------------------------------------+---------------------+-----------+
| db_demo             | 3043a40f-39bf-464e-8337-dc283167b2c3 | us-east1            | ACTIVE    |
+---------------------+--------------------------------------+---------------------+-----------+

$astra db describe db_demo

+------------------------+-----------------------------------------+
| Attribute              | Value                                   |
+------------------------+-----------------------------------------+
| Name                   | db_demo                                 |
| id                     | 3043a40f-39bf-464e-8337-dc283167b2c3    |
| Status                 | ACTIVE                                  |
| Default Cloud Provider | GCP                                     |
| Default Region         | us-east1                                |
| Default Keyspace       | keyspace_demo                           |
| Creation Time          | 2023-04-17T09:03:14Z                    |
| Keyspaces              | [0] demo                                |
| Regions                | [0] us-east1                            |
+------------------------+-----------------------------------------+

4. Api Rest

⚠️ We recommend to use version V2 (with V2 in the URL) as it covers more features and the V1 would be deprecated sooner.

To know more regarding this interface specially you can have a look to dedicated section of the wiki or reference Stargate Rest Api Quick Start Guide.

4.1 Http Client

You need an HTTP Client to use the Rest API. There are a lot of clients in the Java languages like HttpURLConnection, HttpClient introduced in Java 11, Apache HTTPClient, OkHttpClient, Jetty HttpClient. A comparison is provided is this blogpost to make your choice. In this tutorial, we will use the Apache HttpClient, which is included in the SDK. You should adapt the code depending on the framework you have chosen.

Import dependencies in your pom.xml
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>
Standalone Code
import java.io.File;
public class AstraRestApiHttpClient {

    static final String ASTRA_TOKEN       = "<change_with_your_token>";
    static final String ASTRA_DB_ID       = "<change_with_your_database_identifier>";
    static final String ASTRA_DB_REGION   = "<change_with_your_database_region>";
    static final String ASTRA_DB_KEYSPACE = "<change_with_your_keyspace>";

    public static void main(String[] args) throws Exception {

        String apiRestEndpoint = new StringBuilder("https://")
                .append(ASTRA_DB_ID).append("-")
                .append(ASTRA_DB_REGION)
                .append(".apps.astra.datastax.com/api/rest")
                .toString();
        System.out.println("Rest Endpoint is " + apiRestEndpoint);

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Work with HTTP CLIENT
            listKeyspaces(httpClient, apiRestEndpoint);
            createTable(httpClient, apiRestEndpoint);
        }
    }
}
  • Operations
List Keyspaces

  • Code
private static void listKeyspaces(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
        // Build Request
        HttpGet listKeyspacesReq = new HttpGet(apiRestEndpoint + "/v2/schemas/keyspaces");
        listKeyspacesReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

        // Execute Request
        try(CloseableHttpResponse res = httpClient.execute(listKeyspacesReq)) {
        if (200 == res.getCode()) {
        logger.info("[OK] Keyspaces list retrieved");
        logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
}
Creating a table

  • Sample JSON payload createTableJson.
{
  "name": "users",
  "columnDefinitions": [
    {  "name": "firstname", "typeDefinition": "text" },
    {  "name": "lastname",  "typeDefinition": "text" },
    {  "name": "email",     "typeDefinition": "text" },
    {  "name": "color",     "typeDefinition": "text" }
  ],
  "primaryKey": { 
    "partitionKey": ["firstname"],
    "clusteringKey": ["lastname"]
  },
  "tableOptions": {
    "defaultTimeToLive": 0,
    "clusteringExpression": [{ "column": "lastname", "order": "ASC" }]
  }
}
  • Creating the http request using that payload
private static void createTable(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
  HttpPost createTableReq = new HttpPost(apiRestEndpoint
      + "/v2/schemas/keyspaces/" + ASTRA_DB_KEYSPACE + "/tables");
  createTableReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  String createTableJson = "{...JSON.....}";
  createTableReq.setEntity(new StringEntity(createTableJson, ContentType.APPLICATION_JSON));

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(createTableReq)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Table Created (if needed)");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
Insert a new Row

private static void insertRow(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {
  HttpPost insertCedrick = new HttpPost(apiRestEndpoint + "/v2/keyspaces/"
  + ASTRA_DB_KEYSPACE + "/users" );
  insertCedrick.addHeader("X-Cassandra-Token", ASTRA_TOKEN);
  insertCedrick.setEntity(new StringEntity("{"
    + " \"firstname\": \"Cedrick\","
    + " \"lastname\" : \"Lunven\","
    + " \"email\"    : \"c.lunven@gmail.com\","
    + " \"color\"    : \"blue\" }", ContentType.APPLICATION_JSON));

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(insertCedrick)) {
    if (201 == res.getCode()) {
      logger.info("[OK] Row inserted");
      logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
    }
  }
}
Retrieve a row

private static void retrieveRow(CloseableHttpClient httpClient, String apiRestEndpoint)
throws Exception {

  // Build Request
  HttpGet rowReq = new HttpGet(apiRestEndpoint + "/v2/keyspaces/"
    + ASTRA_DB_KEYSPACE + "/users/Cedrick/Lunven" );
  rowReq.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

  // Execute Request
  try(CloseableHttpResponse res = httpClient.execute(rowReq)) {
    if (200 == res.getCode()) {
      String payload =  EntityUtils.toString(res.getEntity());
      logger.info("[OK] Row retrieved");
      logger.info("Row retrieved : {}", payload);
    }
  }
}
Resources

 Download REST HTTP CLIENT

4.2 Java SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.core.domain.RowResultPage;
import io.stargate.sdk.rest.StargateRestApiClient;
import io.stargate.sdk.rest.TableClient;
import io.stargate.sdk.rest.domain.CreateTable;
import io.stargate.sdk.rest.domain.SearchTableQuery;

import java.util.HashMap;
import java.util.Map;

public class AstraSdkRestApi {
    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {
            StargateRestApiClient restApiClient =
                    astraClient.apiStargateData();

            // -- Create a table
            CreateTable createTable = CreateTable.builder()
                    .name("my_table")
                    .addPartitionKey("foo", "text")
                    .addColumn("bar", "text")
                    .ifNotExist(true)
                    .build();
            restApiClient.keyspace("demo")
                    .createTable("my_table", createTable);

            // we can now work on the table
            TableClient tableClient = restApiClient
                    .keyspace("demo")
                    .table("my_table");

            // -- Insert a row
            Map<String, Object> record = new HashMap<>();
            record.put("foo", "Hello");
            record.put("bar", "World");
            tableClient.upsert(record);

            // -- Retrieve rows
            SearchTableQuery query = SearchTableQuery.builder().
                    select("foo", "bar")
                    .where("foo")
                    .isEqualsTo("Hello")
                    .build();
            RowResultPage result = tableClient.search(query);
            System.out.println(result.getResults()
                    .get(0).get("bar"));
        }
    }
}

 Download Project

5. Api Document

The Document API is an HTTP REST API and part of the open source Stargate.io. The idea is to provide an abstraction on top of Apache Cassandra™ to allow document-oriented access patterns. To get familiar with it you can access documentation and sandbox here

5.1 Http Client

Import dependencies in your pom.xml
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>
Standalone Code
static final String ASTRA_TOKEN       = "change_me";
static final String ASTRA_DB_ID       = "change_me";
static final String ASTRA_DB_REGION   = "change_me";
static final String ASTRA_DB_KEYSPACE = "change_me";
static  Logger logger = LoggerFactory.getLogger(AstraDocApiHttpClient.class);

public static void main(String[] args) throws Exception {
   try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        // Build Request
        String apiRestEndpoint = new StringBuilder("https://")
            .append(ASTRA_DB_ID).append("-")
            .append(ASTRA_DB_REGION)
            .append(".apps.astra.datastax.com/api/rest")
            .toString();
        HttpGet req = new HttpGet(apiRestEndpoint + "/v2/schemas/namespaces");
        req.addHeader("X-Cassandra-Token", ASTRA_TOKEN);

        // Execute Request
        try(CloseableHttpResponse res = httpClient.execute(req)) {
          if (200 == res.getCode()) {
            logger.info("[OK] Namespaces list retrieved");
            logger.info("Returned message: {}", EntityUtils.toString(res.getEntity()));
          }
        }
   }
}
Resources

 Download SDK Sample

5.2 Java SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.doc.CollectionClient;
import io.stargate.sdk.doc.Document;
import io.stargate.sdk.doc.StargateDocumentApiClient;

import java.util.stream.Collectors;

public class AstraSdkDocApi {

    // Given a Java POJO
    public static final class User {
        String email;
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateDocumentApiClient apiDoc =
                    astraClient.apiStargateDocument();

            // List namespaces
            System.out.println("- List namespaces  : " + apiDoc
                            .namespaceNames()
                            .collect(Collectors.toList()));

            // List Collection in a Keyspace
            System.out.println("- List collections : " + apiDoc
                    .namespace("demo")
                    .collectionNames()
                    .collect(Collectors.toList()));

            // Create collection
            CollectionClient userCollection = apiDoc
                    .namespace("demo")
                    .collection("user");
            if (!userCollection.exist()) userCollection.create();

            // Working with documents
            User userA = new User();userA.setEmail("a@a.com");
            User userB = new User();userB.setEmail("b@b.com");

            // Create a Document and let Astra create the ID
            String userADocumentId = userCollection.create(userA);
            System.out.println("Document Created: " + userADocumentId);

            // Create a Document with a specific ID
            userCollection.document("b@b.com").upsert(userB);

            // List Documents
            System.out.println("Documents:");
            for(Document<User> doc : userCollection.findPage(User.class).getResults()) {
                System.out.println("" +
                        "- id: " + doc.getDocumentId() +
                        ", email : " + doc.getDocument().getEmail());
            }
        }
    }



}

 Download Project

5.3 Repository Pattern

With modern java applications you want to interact with the DB using the repository pattern where most operations have been implemented for you findAll(), findById().... Astra SDK provide this feature for the document API.

Sample Code
AstraSdkDrivers.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.doc.StargateDocumentRepository;

public class AstraSdkDocRepository {

    // Given a Java POJO
    public static final class User {
        String email;
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .withCqlKeyspace("demo")
                .enableCql()
                .build()) {

            // Doc Repository
            StargateDocumentRepository<User> userRepo =
                    new StargateDocumentRepository<User>(
                            astraClient.apiStargateDocument().namespace("demo"),
                            User.class);

            // Working with documents
            User userA = new User();
            userA.setEmail("a@a.com");
            User userB = new User();
            userB.setEmail("b@b.com");

            // Create Documents
            userRepo.insert(userA);
            userRepo.insert("b@b.com", userB);

            // List Documents
            userRepo.findAll().forEach(doc -> {
                System.out.println(
                        "id=" + doc.getDocumentId()
                        + ", email= " + doc.getDocument().getEmail());
            });

        }
    }
}

 Download Project

6 Api GraphQL

6.1 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Sample Code
AstraSdkGraphQLApi.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.gql.StargateGraphQLApiClient;

public class AstraSdkGraphQLApi {

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateGraphQLApiClient graphClient = astraClient.apiStargateGraphQL();
            graphClient.keyspaceDDL().keyspaces().forEach(k-> System.out.println(k.getName()));
        }
    }
}

 Download Project

7. Api gRPC

7.1 Grpc Client

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
   <dependency>
      <groupId>io.stargate.grpc</groupId>
      <artifactId>grpc-proto</artifactId>
      <version>${latest-grpc-stargate}</version>
  </dependency>
  <dependency>
      <groupId>io.grpc</groupId>
      <artifactId>grpc-netty-shaded</artifactId>
  </dependency>
</dependencies>
Standalone Code
  public class GrpcClient {

    // Define inputs
    static final String ASTRA_DB_TOKEN  = "<provide_a_clientSecret>";
    static final String ASTRA_DB_ID     = "<provide_your_database_id>";
    static final String ASTRA_DB_REGION = "<provide_your_database_region>";

    // Open Grpc communicatino 
    ManagedChannel channel = ManagedChannelBuilder
      .forAddress(ASTRA_DB_ID + "-" + ASTRA_DB_REGION + ".apps.astra.datastax.com", 443)
      .useTransportSecurity()
      .build();

    // use Grpc Stub generated from .proto as a client
    StargateGrpc.StargateBlockingStub cloudNativeClient = StargateGrpc
          .newBlockingStub(channel)
          .withCallCredentials(new StargateBearerToken(ASTRA_DB_TOKEN))
          .withDeadlineAfter(5, TimeUnit.SECONDS);

  // create Query
  String cqlQuery = "SELECT data_center from system.local";

  // Execute the Query
  Response res = cloudNativeClient.executeQuery(QueryOuterClass
                  .Query.newBuilder().setCql(cqlQuery).build());

  // Accessing Row result
  QueryOuterClass.Row row = res.getResultSet().getRowsList().get(0);

  // Access the single value
  String datacenterName = row.getValues(0).getString();
  System.out.println("You are connected to '%s'".formatted(datacenterName));

7.2 Astra SDK

The Astra SDK sets up the connection to work with the AstraDB cloud-based service. You will work with the class AstraClient, Reference documentation.

Import dependencies in your pom.xml
  • Update your pom.xml file with the latest version of the SDK Maven Central
<dependencies>
 <dependency>
     <groupId>com.datastax.astra</groupId>
     <artifactId>astra-sdk</artifactId>
     <version>${latestSDK}</version>
 </dependency>
</dependencies>
Sample Code
AstraSdkGrpcApi.java
package com.datastax.astra;

import com.datastax.astra.sdk.AstraClient;
import io.stargate.sdk.grpc.StargateGrpcApiClient;

public class AstraSdkGrpcApi {

    public static void main(String[] args) {

        // Connect
        try (AstraClient astraClient = AstraClient.builder()
                .withClientId("client_id")
                .withClientSecret("client_secret")
                .withDatabaseId("database_id")
                .withDatabaseRegion("database_region")
                .build()) {

            StargateGrpcApiClient grpcClient = astraClient.apiStargateGrpc();
            System.out.println("+ Cql Version (grpc)  : " + grpcClient
                    .execute("SELECT cql_version from system.local")
                    .one().getString("cql_version"));
        }

    }
}

 Download Project


Last update: 2023-05-04