Java driver quickstart

DataStax recommends the Data API and clients for Serverless (Vector) databases. You can use the Data API to perform CQL operations on your table data in Serverless (Vector) databases.

DataStax recommends drivers only for Serverless (Non-Vector) databases, legacy applications that rely on a driver, or for CQL functions that aren’t supported by the Data API. For more information, see Compare connection methods.

To use the DataStax Java driver, you need to add the driver dependency to your pom.xml, use the ConnectDatabase class to initialize the driver, and then connect the driver to your Astra DB Serverless database. Once connected, your scripts can use the driver to run commands against your database.

This quickstart explains how to use the Java driver to connect to a Serverless (Vector) database, create a table, create an vector-compatible index, load data with vector embeddings, and perform a similarity search. It also includes instructions to migrate an existing DataStax Java driver to a version that supports Astra DB.

Prerequisites

  1. Create a database.

  2. Set the following environment variables:

    • ASTRA_DB_ID: The database ID

    • ASTRA_DB_REGION: A region where your database is deployed and where you want to connect to the database, such as us-east-2

    • ASTRA_DB_KEYSPACE: A keyspace in your database, such as default_keyspace

    • ASTRA_DB_APPLICATION_TOKEN: An application token with the Database Administrator role.

      The token.json has the following format:

      {
        "clientId": "CLIENT_ID",
        "secret": "CLIENT_SECRET",
        "token": "APPLICATION_TOKEN"
      }

      For driver authentication, you can use either clientId and secret or the literal string token and the AstraCS token value. If you are on an older driver version that doesn’t support the token option, then you might need to use clientId and secret. For more information, see Token details.

  3. Download your database’s Secure Connect Bundle (SCB).

  4. Install Maven.

  5. Install a current Java version.

Add the Java driver dependency

  1. Add the latest DataStax Java driver Latest cassandra-java-driver release on GitHub dependency to your project’s pom.xml file.

    Serverless (Vector) databases require Java driver version 4.17.0 or later.

    <dependency>
      <groupId>com.datastax.oss</groupId>
      <artifactId>java-driver-core</artifactId>
      <version>VERSION</version>
    </dependency>

    Make sure you use a driver version that is compatible with Astra DB. For more information, see DataStax driver matrix.

Initialize and connect the Java driver

  1. In your Java project, navigate to /src/main/java, and then create a ConnectDatabase.java file:

    cd JAVA_PROJECT_DIRECTORY/src/main/java
    touch ConnectDatabase.java
  2. Copy the following code into ConnectDatabase.java, and then replace PATH_TO_SCB with the absolute path to your database’s Secure Connect Bundle (SCB) (secure-connect-DATABASE_NAME.zip):

    ConnectDatabase.java
    import com.datastax.oss.driver.api.core.CqlSession;
    import com.datastax.oss.driver.api.core.cql.ResultSet;
    import com.datastax.oss.driver.api.core.cql.Row;
    import com.datastax.oss.driver.api.core.CqlSessionBuilder;
    import com.datastax.oss.driver.api.core.cql.PreparedStatement;
    import com.datastax.oss.driver.api.core.data.CqlVector;
    import com.datastax.oss.driver.api.core.type.codec.TypeCodecs;
    
    import java.nio.file.Paths;
    import java.util.Arrays;
    import java.util.List;
    
    public class VectorTest {
        public static void main(String[] args) {
            // Initialize the Java driver
            CqlSessionBuilder builder = CqlSession.builder();
            builder.withCloudSecureConnectBundle(Paths.get("**PATH_TO_SCB**"));
            builder.withAuthCredentials("token", System.getenv("ASTRA_DB_APPLICATION_TOKEN"));
            builder.withKeyspace(System.getenv("ASTRA_DB_KEYSPACE"));
    
            try (CqlSession session = builder.build()) {
                // ...
            }
        }
    }

    This code imports the necessary classes, sets up a CqlSession with an SCB, authenticates credentials, and specifies a default keyspace.

  3. Save ConnectDatabase.java and then build your Maven project to test the connection.

Run commands with the Java driver

After you connect to the database, you can use the driver to perform operations on your database.

Create a table and vector index

The following code creates a table named vector_test with columns for an integer id, text, and a 5-dimensional vector. Then, it creates a custom index on the vector column using dot product similarity function for efficient vector searches.

// ...
            session.execute(String.format(
                "CREATE TABLE IF NOT EXISTS vector_test (id INT PRIMARY KEY, " +
                "text TEXT, vector VECTOR<FLOAT,%d>);",
                v_dimension)
            );

            session.execute(String.format(
                "CREATE CUSTOM INDEX IF NOT EXISTS idx_vector_test ON vector_test " +
                "(vector) USING 'StorageAttachedIndex' WITH OPTIONS = {'similarity_function' : 'cosine'};")
            );
// ...

Load data

The following code loads some rows with embeddings into the vector_test table.

// ...
            List<Object[]> textBlocks = Arrays.asList(
                new Object[]{1, "Chat bot integrated sneakers that talk to you", CqlVector.newInstance(Arrays.asList(0.1f, 0.15f, 0.3f, 0.12f, 0.05f))},
                new Object[]{2, "An AI quilt to help you sleep forever", CqlVector.newInstance(Arrays.asList(0.45f, 0.09f, 0.01f, 0.2f, 0.11f))},
                new Object[]{3, "A deep learning display that controls your mood", CqlVector.newInstance(Arrays.asList(0.1f, 0.05f, 0.08f, 0.3f, 0.6f))}
            );

            PreparedStatement ps = session.prepare(String.format(
                "INSERT INTO vector_test (id, text, vector) VALUES (?, ?, ?)")
            );
            for (Object[] block : textBlocks) {
                session.execute(ps.bind(block));
            }
// ...

The following code performs a similarity search to find rows that are close to a specific vector embedding.

// ...
            String annQuery = String.format(
                "SELECT id, text, similarity_cosine(vector, [0.15, 0.1, 0.1, 0.35, 0.55]) as sim " +
                "FROM vector_test " +
                "ORDER BY vector ANN OF [0.15, 0.1, 0.1, 0.35, 0.55] LIMIT 2"
            );

            ResultSet rs = session.execute(annQuery);
            for (Row row : rs) {
                System.out.printf("[%d] \"%s\" (sim: %.4f)\n", row.getInt("id"), row.getString("text"), row.getFloat("sim"));
            }
// ...

Migrate the Java driver

You can migrate an earlier DataStax Java driver to a version that supports Astra DB.

  1. Complete the prerequisites.

  2. In your pom.xml, update the Java driver version:

    <dependency>
      <groupId>com.datastax.oss</groupId>
      <artifactId>java-driver-core</artifactId>
      <version>VERSION</version>
    </dependency>
  3. In your existing Java driver code, modify the connection code to use the SCB credentials. For more information, see Initialize and connect the Java driver.

            CqlSessionBuilder builder = CqlSession.builder();
            builder.withCloudSecureConnectBundle(Paths.get("PATH_TO_SCB"));
            builder.withAuthCredentials("token", System.getenv("ASTRA_DB_APPLICATION_TOKEN"));
  4. Build your project.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2025 DataStax | Privacy policy | Terms of use

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: +1 (650) 389-6000, info@datastax.com