Connect with the Java driver
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 Connect to a database. |
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 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 and send some CQL statements to the database. It also includes instructions to migrate an existing Java driver to a version that supports Astra DB.
Prerequisites
-
Install Maven.
-
Install a current Java version.
-
Download your database’s Secure Connect Bundle (SCB).
For multi-region databases, download the Secure Connect Bundle (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 Secure Connect Bundle (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:
-
ASTRA_DB_ID
: The database ID. -
KEYSPACE_NAME
: A keyspace in your database, such asdefault_keyspace
. -
APPLICATION_TOKEN
: An application token with the Database Administrator role.
-
Driver authentication methods
There are two driver authentication methods: token
authentication, or clientId
and secret
authentication.
-
Token authentication
-
Client ID and secret authentication
This authentication method is supported and recommended for most recent driver versions.
In your driver authentication code, pass the literal string token
as the username and your application token value (AstraCS:…
) as the password.
For example:
("token", "AstraCS:...")
If you are on an older driver version that doesn’t support token
authentication, then you might need to use clientId
and secret
.
When you generate an application token, download or copy the token.json
that contains the following values:
{
"clientId": "CLIENT_ID",
"secret": "CLIENT_SECRET",
"token": "APPLICATION_TOKEN"
}
In your driver authentication code, pass clientId
as the username and secret
as the password.
For example:
("CLIENT_ID", "SECRET")
For more information, see Token details.
Add the Java driver dependency
-
In your project’s
pom.xml
file, add a dependency for the Apache Cassandra Java driver.
-
Latest version
-
Version 4.17 and earlier
<dependency> <groupId>org.apache.cassandra</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency>
<dependency> <groupId>com.datastax.oss</groupId> <artifactId>java-driver-core</artifactId> <version>VERSION</version> </dependency>
If you choose to install an earlier version, make sure you choose a version that is compatible with Astra DB. If you need to query vector data, make sure your chosen version also supports vector data. For more information, see Cassandra drivers supported by DataStax.
-
Initialize and connect the Java driver
-
In your Java project, navigate to
/src/main/java
, and then create aConnectDatabase.java
file:cd JAVA_PROJECT_DIRECTORY/src/main/java touch ConnectDatabase.java
-
Copy the following code into
ConnectDatabase.java
, and then replacePATH_TO_SCB
with the absolute path to your database’s Secure Connect Bundle (SCB) (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")); builder.withAuthCredentials("token", System.getenv("APPLICATION_TOKEN")); builder.withKeyspace(System.getenv("KEYSPACE_NAME")); 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.
-
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.
Submit a simple CQL statement
The following code connects to an Astra DB database, runs a CQL SELECT
statement, and then prints the output to the console:
// Import dependencies
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("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);
}
}
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'};")
);
// ...
Insert data
The following code inserts 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));
}
// ...
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 your driver from an earlier version 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
groupId
andversion
.<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
token
authentication. 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("APPLICATION_TOKEN"));
-
Build your project.