Connect with the Java driver
|
DataStax recommends the Data API and clients for Serverless (vector) databases. You can use the Data API to run CQL statements on tables in Serverless (vector) databases. DataStax recommends drivers only for Serverless (non-vector) databases, legacy applications that rely on a driver, or CQL functions that aren’t supported by the Data API. For more information, see Connect to Astra DB Serverless databases. |
Because Astra DB is based on Apache Cassandra®, you can use Cassandra drivers to connect to your Astra DB Serverless databases.
To use the 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 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 an Astra DB Serverless database and send some Cassandra Query Language (CQL) statements to the database. It also explains how to upgrade from an earlier version of the Java driver to a version that supports Astra DB.
Prerequisites
-
Install Apache Maven™.
-
Install a current Java version.
-
Download your database’s Secure Connect Bundle (SCB).
For multi-region databases, download the SCB for a region that is geographically close to your application to reduce latency.
If you need to connect to multiple regions in the same application, you need the SCB for each region, and your driver code must instantiate one root object (
session) for each region. For more information, see Best practices for Cassandra drivers. -
Set the following environment variables:
-
DATABASE_ID: The database ID. -
APPLICATION_TOKEN: An application token with the Database Administrator role.
-
Driver authentication methods
There are two driver authentication methods:
tokenauthentication-
The
tokenauthentication method is supported and recommended for most recent driver versions.In your driver authentication code, pass the literal string
tokenas the username and your application token value (AstraCS:…) as the password. For example:("token", "AstraCS:...") clientIdandsecretauthentication-
If you are on an older driver version that doesn’t support
tokenauthentication, then you might need to useclientIdandsecret.When you generate an application token, download or copy the
token.jsonthat contains the following values:{ "clientId": "CLIENT_ID", "secret": "CLIENT_SECRET", "token": "APPLICATION_TOKEN" }Then, in your driver authentication code, pass
clientIdas the username andsecretas the password. For example:("CLIENT_ID", "SECRET")
For more information, see Token details.
Add the Java driver dependency
-
In your project’s
pom.xmlfile, add a dependency for the Apache Cassandra Java driver.
If you install an earlier version of the driver, make sure your version is compatible with Astra DB. If you need to query vector data in Astra DB Serverless (vector) databases, make sure your version also supports vector data. For more information, see Cassandra drivers supported by DataStax.
The
groupIddepends on the driver version:- Version 4.18 and later
-
<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency> - Version 4.17 and earlier
-
<dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency>
Initialize and connect the Java driver
-
In your Java project, navigate to
/src/main/java, and then create aConnectDatabase.javafile:cd JAVA_PROJECT_DIRECTORY/src/main/java touch ConnectDatabase.java -
Copy the following code into
ConnectDatabase.java, and then replacePATH/TO/SCB.zipwith the absolute path to your database’s Secure Connect Bundle (SCB) zip file (secure-connect-DATABASE_NAME.zip):ConnectDatabase.javaimport 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.zip")); builder.withAuthCredentials("token", System.getenv("APPLICATION_TOKEN")); builder.withKeyspace(System.getenv("KEYSPACE_NAME")); try (CqlSession session = builder.build()) { // Select the release_version from the system.local table: ResultSet rs = session.execute("select release_version from system.local"); Row row = rs.one(); //Print the results of the CQL query to the console: if (row != null) { System.out.println(row.getString("release_version")); } else { System.out.println("An error occurred."); } } System.exit(0); } }This code imports dependencies, initializes the Java driver, implements the
ConnectDatabaseclass to connect to your Astra DB Serverless database, runs a CQL query, and then prints the output to the console.The example
SELECTstatement runs against thesystem.localtable. You can replace this statement with any CQL statement on any keyspace or table in your database. Edit theKEYSPACE_NAMEenvironment variable, if necessary. -
Save
ConnectDatabase.java, and then build your Maven project.If you ran the example
SELECTstatement on thesystem.localtable, then thecluster_namevalue from thesystem.localtable is printed to the console if the script runs successfully.
Run a vector search with the Java driver
The following example shows how you can use the Java driver to index vector data and then run a vector search:
-
Create a table and vector index.
The following code creates a table named
vector_testwith 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'};") ); // ... -
Insert vector data.
The following code inserts some rows with embeddings into the
vector_testtable:// ... 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)); } // ... -
Perform a vector search.
The following code performs a vector 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")); } // ...
Upgrade the Java driver
Use these steps if you need to upgrade from an earlier version of the Java driver to a version that supports Astra DB:
-
In your pom.xml, update the dependency for the Apache Cassandra Java driver
.
If you are upgrading from a version earlier than 4.18.0, make sure that you update the
groupIdas well as theversion:<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency> -
In your existing Java driver code, modify the connection code to use the SCB and
tokenauthentication:CqlSessionBuilder builder = CqlSession.builder(); builder.withCloudSecureConnectBundle(Paths.get("PATH/TO/SCB.zip")); builder.withAuthCredentials("token", System.getenv("APPLICATION_TOKEN"));For more information, see Initialize and connect the Java driver.
-
Build your project.
Next steps
You can extend or modify the example script used in this guide to run other commands against your database, or connect to other databases. For more information, see the following: