Connect the Java driver to your database

DataStax recommends using the Java client with DSE databases. Use the Java driver only if you are working with an existing application that previously used a CQL-based driver or if you plan to explicitly use CQL.

Initialize the Java driver to connect to your database.

Prerequisite

Connect

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

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 DriverExample {
    public static void main(String[] args) {
        // Initialize the Java driver
        String keyspace = "default_keyspace";
        CqlSessionBuilder builder = CqlSession.builder();
        builder.withAuthCredentials("user_name","password");
        builder.withKeyspace(keyspace);

        try (CqlSession session = builder.build()) {
            int v_dimension = 5;
            // ...
        }
    }
}

See the Java quickstart for details on how to add dependencies, connect to a DSE database, create a table and vector-compatible SAI (Storage-Attached Index), load data, and perform a similarity search.

Was this helpful?

Give Feedback

How can we improve the documentation?

© 2024 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