### Start Creating a Table Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/table/README.md Initiates a CREATE TABLE query. Use this as the starting point for defining a new table schema. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; CreateTableStart create = createTable("cycling", "cyclist_name"); ``` -------------------------------- ### Install Project with Maven Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md If encountering issues with shaded classes in an IDE, use this command to clean and install the project locally. ```bash mvn clean install -DskipTests ``` -------------------------------- ### Example Commit Message with Details Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md A concrete example of a commit message following the specified format, including a JIRA key, title, and reviewer names. ```txt CASSJAVA-108 Update ESRI (and remove org.json) dependencies patch by Bret McGuire; reviewed by Bret McGuire and Lukasz Antoniak ``` -------------------------------- ### Install Project with Maven (IDE Issues) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md If encountering issues with shaded classes in an IDE like IntelliJ, use this command to install the project locally. This is an alternative to 'package' for resolving dependency conflicts. ```bash mvn clean install -DskipTests ``` -------------------------------- ### Start SELECT Query Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/select/README.md Begin building a SELECT query by specifying the table name. This is the initial step before adding selectors. ```java import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*; SelectFrom selectUser = selectFrom("user"); ``` -------------------------------- ### Basic SELECT Query with Query Builder Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/README.md Example of building and executing a simple SELECT query using the query builder and CqlSession. ```java import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*; try (CqlSession session = CqlSession.builder().build()) { Select query = selectFrom("system", "local").column("release_version"); // SELECT release_version FROM system.local SimpleStatement statement = query.build(); ResultSet rs = session.execute(statement); Row row = rs.one(); System.out.println(row.getString("release_version")); } ``` -------------------------------- ### Logback INFO Example: Configuration Change Detected Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/logging/README.md This log indicates that a configuration change has been detected by the driver. ```log INFO c.d.o.d.i.c.c.t.DefaultDriverConfigLoader - [s0] Detected a configuration change ``` -------------------------------- ### Unsupported Protocol Version Error Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/native_protocol/README.md An example of an exception that occurs when the driver attempts to use a protocol version that is not supported by the Cassandra server. ```java Exception in thread "main" com.datastax.oss.driver.api.core.AllNodesFailedException: All 1 node tried for the query failed (showing first 1 nodes, use getAllErrors() for more: /127.0.0.1:9042: com.datastax.oss.driver.api.core.UnsupportedProtocolVersionException: [/127.0.0.1:9042] Host does not support protocol version V5) ``` -------------------------------- ### Build the Project with Maven Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Use this command to clean and package the project, skipping tests. Ensure Java 8 and Maven 3.8.1+ are installed. ```bash mvn clean package -DskipTests ``` -------------------------------- ### Start Creating a Materialized View Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/materialized_view/README.md Initiates a CREATE MATERIALIZED VIEW query. Import static SchemaBuilder.* to use this method. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; CreateMaterializedViewStart create = createMaterializedView("cycling", "cyclist_by_age"); ``` -------------------------------- ### Logback INFO Example: Native Clock Usage Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/logging/README.md This log confirms that the native clock is being used for microsecond precision. ```log INFO c.d.o.d.internal.core.time.Clock - Using native clock for microsecond precision ``` -------------------------------- ### Initialize component with InternalDriverContext Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/developer/common/context/README.md Example of a component constructor extracting dependencies from the context to avoid manual initialization ordering. ```java public DefaultTopologyMonitor(InternalDriverContext context) { ... this.controlConnection = context.getControlConnection(); } ``` -------------------------------- ### Obtain DAO and Execute Query Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/README.md Obtain a DAO instance from the mapper and execute queries. This example shows saving a new product. ```java ProductDao dao = inventoryMapper.productDao(CqlIdentifier.fromCql("inventory")); dao.save(new Product(UUID.randomUUID(), "Mechanical keyboard")); ``` -------------------------------- ### Example of a Class-Level Rule Chain Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md Demonstrates how to combine a CcmRule and a SessionRule using RuleChain for proper initialization order in integration tests. ```java private static final CcmRule CCM_RULE = CcmRule.getInstance(); private static final SessionRule SESSION_RULE = SessionRule.builder(CCM_RULE).build(); @ClassRule public static final TestRule CHAIN = RuleChain.outerRule(CCM_RULE).around(SESSION_RULE); ``` -------------------------------- ### Proxy Authentication Configuration (GSSAPI/Kerberos) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/authentication/README.md Example of configuring proxy authentication with GSSAPI (Kerberos) in application.conf. ```java datastax-java-driver { advanced.auth-provider { class = DseGssApiAuthProvider authorization-id = alice login-configuration { principal = "user principal here ex bob@DATASTAX.COM" useKeyTab = "true" refreshKrb5Config = "true" keyTab = "Path to keytab file here" } } } ``` -------------------------------- ### Initialize CREATE FUNCTION query Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/function/README.md Start a function creation query using the SchemaBuilder API. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; CreateFunctionStart create = createFunction("log"); ``` -------------------------------- ### Mocking dependencies with Mockito Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Example of configuring mock behavior and verifying method invocations. ```java when(codecRegistry.codecFor(DataTypes.INT)).thenReturn(codec); verify(codec).decodePrimitive(any(ByteBuffer.class), eq(ProtocolVersion.DEFAULT)); ``` -------------------------------- ### Initialize CREATE AGGREGATE query Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/aggregate/README.md Start a CREATE AGGREGATE statement using the SchemaBuilder. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; CreateAggregateStart create = createAggregate("average"); ``` -------------------------------- ### Logback INFO Example: Default Contact Points Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/logging/README.md This log indicates that no contact points were provided and the driver is defaulting to /127.0.0.1:9042. ```log INFO c.d.o.d.i.c.metadata.MetadataManager - [s0] No contact points provided, defaulting to /127.0.0.1:9042 ``` -------------------------------- ### Initialize GraphTraversalSource Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/dse/graph/fluent/README.md Example of initializing a GraphTraversalSource for building Gremlin traversals. The exact initialization depends on the execution model. ```java GraphTraversalSource g = ... GraphTraversal traversal = g.V().has("name", "marko"); ``` -------------------------------- ### Proxy Authentication Configuration (Plain Text) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/authentication/README.md Example of configuring proxy authentication with plain text credentials in application.conf. ```java datastax-java-driver { advanced.auth-provider { class = PlainTextAuthProvider username = bob password = bob's password authorization-id = alice } } ``` -------------------------------- ### Initialize Create Index Query Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/index/README.md Start a CREATE INDEX query using the SchemaBuilder. The index name is optional and the keyspace is inferred from the table. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; // an index name is not required CreateIndexStart create = createIndex(); create = createIndex("my_idx"); ``` -------------------------------- ### Run Unit Tests with Maven Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Execute unit tests after building the project. This command first installs the project and then runs the tests. ```bash mvn clean install -DskipTests mvn test ``` -------------------------------- ### Instantiate DAOs with Different Configurations Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/mapper/README.md Demonstrates how to instantiate ProductDao instances using the InventoryMapper, specifying different combinations of keyspace and table. ```java ProductDao dao1 = inventoryMapper.productDao(); ProductDao dao2 = inventoryMapper.productDao("keyspace2"); ProductDao dao3 = inventoryMapper.productDao("keyspace3", "table3"); ``` -------------------------------- ### Example Squashed Commit Message Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md An example of a correctly formatted squashed commit message for a pull request. ```text CASSJAVA-108 Update ESRI (and remove org.json) dependencies patch by Bret McGuire; reviewed by Bret McGuire and Lukasz Antoniak ``` -------------------------------- ### Synchronous Paging Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/paging/README.md Iterate through results; the driver fetches subsequent pages in the background as needed. The fetch size limits results per page. ```java ResultSet rs = session.execute("SELECT * FROM my_table WHERE k = 1"); for (Row row : rs) { // process the row } ``` -------------------------------- ### TaggingMetricIdGenerator with Prefix Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of TaggingMetricIdGenerator generating a session metric identifier with a global prefix 'cassandra'. ```text cassandra.session.bytes-sent ``` -------------------------------- ### Create Keyspace and Table using SchemaBuilder Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/README.md Demonstrates how to create a keyspace with a simple strategy and then create a table with a partition key and columns using the SchemaBuilder API. Ensure a CqlSession is available. ```java import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*; try (CqlSession session = CqlSession.builder().build()) { CreateKeyspace createKs = createKeyspace("cycling").withSimpleStrategy(1); session.execute(createKs.build()); CreateTable createTable = createTable("cycling", "cyclist_name") .withPartitionKey("id", DataTypes.UUID) .withColumn("lastname", DataTypes.TEXT) .withColumn("firstname", DataTypes.TEXT); session.execute(createTable.build()); } ``` -------------------------------- ### Preparing a Query with a Bind Marker Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/README.md Shows how to build a query using the query builder and then prepare it with a bind marker for runtime execution. This is recommended for queries used often. ```java // During application initialization: Select selectUser = selectFrom("user").all().whereColumn("id").isEqualTo(bindMarker()); // SELECT * FROM user WHERE id=? PreparedStatement preparedSelectUser = session.prepare(selectUser.build()); // At runtime: session.execute(preparedSelectUser.bind(userId)); ``` -------------------------------- ### DefaultMetricIdGenerator with Prefix Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of DefaultMetricIdGenerator generating a session metric identifier with a global prefix 'cassandra'. ```text cassandra.s0.bytes-sent ``` -------------------------------- ### Get UserDefinedType from an Existing UdtValue Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/udts/README.md Illustrates how to get the UserDefinedType associated with an already existing UdtValue object. ```java UserDefinedType udt = udtValue.getType(); ``` -------------------------------- ### Configure Session with Default Keyspace Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/mapper/README.md Shows how to build a CqlSession with a default keyspace and then use it to build an InventoryMapper to create a ProductDao that uses the default keyspace. ```java CqlSession session = CqlSession.builder().withKeyspace("keyspace1").build(); InventoryMapper inventoryMapper = new InventoryMapperBuilder(session).build(); ProductDao dao1 = inventoryMapper.productDao(); ``` -------------------------------- ### Preparing a Statement with Execution Parameters Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/prepared/README.md Demonstrates how to prepare a statement using a `SimpleStatement` that includes execution parameters like consistency level. These parameters are then propagated to the bound statement. ```java SimpleStatement simpleStatement = SimpleStatement.builder("SELECT * FROM product WHERE sku = ?") .setConsistencyLevel(DefaultConsistencyLevel.QUORUM) .build(); PreparedStatement preparedStatement = session.prepare(simpleStatement); BoundStatement boundStatement = preparedStatement.bind(); assert boundStatement.getConsistencyLevel() == DefaultConsistencyLevel.QUORUM; ``` -------------------------------- ### TaggingMetricIdGenerator with Prefix Example (Node Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of TaggingMetricIdGenerator generating a node metric identifier with a global prefix 'cassandra'. ```text cassandra.nodes.bytes-sent ``` -------------------------------- ### Quick Start: Connect and Query Cassandra Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/README.md A basic Java program demonstrating how to connect to Cassandra, execute a query, and retrieve data using the synchronous API. Ensure CqlSession is closed after use. ```java import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.*; try (CqlSession session = CqlSession.builder().build()) { ResultSet rs = session.execute("select release_version from system.local"); Row row = rs.one(); System.out.println(row.getString("release_version")); } ``` -------------------------------- ### DefaultMetricIdGenerator with Prefix Example (Node Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of DefaultMetricIdGenerator generating a node metric identifier with a global prefix 'cassandra'. ```text cassandra.s0.nodes.10_1_2_3:9042.bytes-sent ``` -------------------------------- ### Start Altering a Table Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/table/README.md Initiates an ALTER TABLE query. This is the starting point for modifying an existing table's schema. ```java alterTable("cycling", "cyclist_name"); ``` -------------------------------- ### Initialize DAOs with Schema Validation Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/mapper/README.md Illustrates initializing ProductDao instances with specific keyspace and table names, triggering schema validation against the database. ```java // Checks that entity 'Product' can be mapped to table or UDT 'keyspace1.product' ProductDao dao1 = inventoryMapper.productDao("keyspace1", "product"); // Checks that entity 'Product' can be mapped to table or UDT 'keyspace2.product' ProductDao dao2 = inventoryMapper.productDao("keyspace2", "product"); ``` -------------------------------- ### Example Commit Message Format Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md This is an example of the required commit message format for pull requests, including JIRA information and reviewer names. ```txt patch by ; reviewed by and ``` -------------------------------- ### TaggingMetricIdGenerator Example (Node Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of how TaggingMetricIdGenerator generates an identifier for a node metric named 'bytes-sent' for a session named 's0' and node address '10.1.2.3:9042'. ```text name: nodes.bytes-sent tags: { "session" : "s0", "node" : "10.1.2.3:9042" } ``` -------------------------------- ### Basic Prepared Statement Usage Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/prepared/README.md Demonstrates how to prepare an insert statement and execute it with bound values. Use this for queries that are executed frequently. ```java PreparedStatement prepared = session.prepare( "insert into product (sku, description) values (?, ?)"); BoundStatement bound = prepared.bind("234827", "Mouse"); session.execute(bound); ``` -------------------------------- ### DefaultMetricIdGenerator Example (Node Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of how DefaultMetricIdGenerator generates an identifier for a node metric named 'bytes-sent' for a session named 's0' and node address '10.1.2.3:9042'. ```text name : s0.nodes.10_1_2_3:9042.bytes-sent tags: {} ``` -------------------------------- ### Asynchronous Session Opening and Query Execution Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/async/README.md Demonstrates how to open a session asynchronously and chain a query execution. Callbacks execute on I/O threads, so be mindful of expensive computations and error handling. Ensure sessions are closed. ```java CompletionStage sessionStage = CqlSession.builder().buildAsync(); // Chain one async operation after another: CompletionStage responseStage = sessionStage.thenCompose( session -> session.executeAsync("SELECT release_version FROM system.local")); // Apply a synchronous computation: CompletionStage resultStage = responseStage.thenApply(resultSet -> resultSet.one().getString("release_version")); // Perform an action once a stage is complete: resultStage.whenComplete( (version, error) -> { if (error != null) { System.out.printf("Failed to retrieve the version: %s%n", error.getMessage()); } else { System.out.printf("Server version: %s%n", version); } sessionStage.thenAccept(CqlSession::closeAsync); }); ``` -------------------------------- ### Driver 3 vs Driver 4 Basic Query Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/upgrade_guide/README.md Compares the syntax for executing a simple query between Driver 3 and Driver 4. Note the changes in imports and how SimpleStatement is instantiated. ```java // Driver 3: import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; import com.datastax.driver.core.SimpleStatement; SimpleStatement statement = new SimpleStatement("SELECT release_version FROM system.local"); ResultSet resultSet = session.execute(statement); Row row = resultSet.one(); System.out.println(row.getString("release_version")); // Driver 4: 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.cql.SimpleStatement; SimpleStatement statement = SimpleStatement.newInstance("SELECT release_version FROM system.local"); ResultSet resultSet = session.execute(statement); Row row = resultSet.one(); System.out.println(row.getString("release_version")); ``` -------------------------------- ### DSE Geospatial Predicate Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/dse/graph/fluent/README.md Use the Geo class to apply DSE geospatial predicates. This example finds vertices within a specified geographic radius. ```java GraphTraversal traversal = g.V().has("location", "point", Geo.inside(Geo.point(2.352222, 48.856614), 4.2, Geo.Unit.DEGREES)).values("name"); ``` -------------------------------- ### Create and Use a Point Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/dse/geotypes/README.md Demonstrates how to create a Point instance from coordinates and access its X and Y values. ```java Point point = Point.fromCoordinates(2.2945, 48.8584); System.out.println(point.X()); System.out.println(point.Y()); ``` -------------------------------- ### Extracting a Range from a Collection (Open-Ended Start) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/select/README.md Demonstrates selecting elements from a collection starting from a specific index to the end. Use this when you need a suffix of a list or set. ```java selectFrom("movie").range("ratings", literal(3), null); // SELECT ratings[3..] FROM movie ``` -------------------------------- ### Java Stream API Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md Example of using Java's Stream API to map strings to their lengths and collect into a list. This is presented as a contrast to traditional for-loops. ```java List sizes = words.stream().map(String::length).collect(Collectors.toList()); ``` -------------------------------- ### DSE Search Predicate Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/dse/graph/fluent/README.md Use the Search class to apply DSE search predicates to graph traversals. This example filters vertices based on a search token. ```java GraphTraversal traversal = g.V().has("recipe", "instructions", Search.token("Saute")).values("name"); ``` -------------------------------- ### Instantiate Mapper with Session Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/mapper/README.md Shows how to create an instance of a mapper by wrapping a core CqlSession using its generated builder. The session is required to build the mapper. ```java import com.datastax.oss.driver.api.core.CqlSession; CqlSession session = CqlSession.builder().build(); InventoryMapper inventoryMapper = new InventoryMapperBuilder(session).build(); ``` -------------------------------- ### Initialize CqlSession Source: https://github.com/apache/cassandra-java-driver/blob/4.x/upgrade_guide/README.md Initialize the CqlSession, which is now the main component. The session is initialized in a single step. ```java CqlSession session = CqlSession.builder().build(); session.execute("..."); ``` -------------------------------- ### TaggingMetricIdGenerator Example (Session Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of how TaggingMetricIdGenerator generates an identifier for a session metric named 'bytes-sent' for a session named 's0'. This generator is suitable for libraries that support tags. ```text name: session.bytes-sent tags: { "session" : "s0" } ``` -------------------------------- ### DefaultMetricIdGenerator Example (Session Metric) Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metrics/README.md Example of how DefaultMetricIdGenerator generates an identifier for a session metric named 'bytes-sent' for a session named 's0'. This generator is suitable for libraries that do not support tags. ```text name: s0.bytes-sent tags: {} ``` -------------------------------- ### Setting Routing Information for Simple Statements Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/load_balancing/README.md Demonstrates how to manually set the keyspace and routing key for a simple statement. This is necessary when routing information is not automatically computed. ```java SimpleStatement statement = SimpleStatement.newInstance( "SELECT * FROM testKs.sensor_data WHERE id = 1 and year = 2016"); // No routing info available: assert statement.getRoutingKeyspace() == null; assert statement.getRoutingKey() == null; // Set the keyspace manually (skip this if using a per-query keyspace): statement = statement.setRoutingKeyspace("testKs"); // Set the routing key manually: serialize each partition key component to its target CQL type statement = statement.setRoutingKey( TypeCodecs.INT.encodePrimitive(1, session.getContext().getProtocolVersion()), TypeCodecs.INT.encodePrimitive(2016, session.getContext().getProtocolVersion())); session.execute(statement); ``` -------------------------------- ### Synchronous API Blocking Call Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/developer/common/concurrency/README.md This example shows a blocking method within the synchronous API. It includes a check to ensure it's not called on driver I/O threads to prevent deadlocks. ```java public interface ExecutionInfo { // some content omitted for brevity default QueryTrace getQueryTrace() { BlockingOperation.checkNotDriverThread(); return CompletableFutures.getUninterruptibly(getQueryTraceAsync()); } } ``` -------------------------------- ### Create Keyspace, Table, Insert Data, and Query Vector Search Source: https://github.com/apache/cassandra-java-driver/blob/4.x/upgrade_guide/README.md Demonstrates how to create a keyspace and table with a vector column, insert data, and perform a vector search query. Retrieves vector data using `Row.getVector()` and checks its dimensions. ```java try (CqlSession session = new CqlSessionBuilder().withLocalDatacenter("datacenter1").build()) { session.execute("DROP KEYSPACE IF EXISTS test"); session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}"); session.execute("CREATE TABLE test.foo(i int primary key, j vector)"); session.execute("CREATE CUSTOM INDEX ann_index ON test.foo(j) USING 'StorageAttachedIndex'"); session.execute("INSERT INTO test.foo (i, j) VALUES (1, [8, 2.3, 58])"); session.execute("INSERT INTO test.foo (i, j) VALUES (2, [1.2, 3.4, 5.6])"); session.execute("INSERT INTO test.foo (i, j) VALUES (5, [23, 18, 3.9])"); ResultSet rs=session.execute("SELECT j FROM test.foo WHERE j ann of [3.4, 7.8, 9.1] limit 1"); for (Row row : rs){ CqlVector v = row.getVector(0, Float.class); System.out.println(v); if (Iterables.size(v) != 3) { throw new RuntimeException("Expected vector with three dimensions"); } } } ``` -------------------------------- ### Define function with JavaScript Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/query_builder/schema/function/README.md Example of defining a function using JavaScript and automatic quoting. ```java createFunction("sayhi") .withParameter("input", DataTypes.TEXT) .returnsNullOnNull() .returnsType(DataTypes.TEXT) .withJavaScriptLanguage() .asQuoted("'hi ' + input;"); ``` -------------------------------- ### Waiting for conditions with Awaitility Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Example of using Awaitility to poll for a condition to become true. ```java await().until(() -> somethingBecomesTrue()); ``` -------------------------------- ### Setting System Query Programmatically Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/dse/graph/options/README.md Demonstrates the programmatic alternative to setting a system query, using the `setSystemQuery(true)` method. ```java // Programmatic alternative: ScriptGraphStatement statement = ScriptGraphStatement.newInstance("system.graph('demo').ifNotExists().create()") .setSystemQuery(true); ``` -------------------------------- ### Create Simple Statement with newInstance() Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/simple/README.md Shows how to create a simple statement using the static newInstance() factory method. ```java SimpleStatement statement = SimpleStatement.newInstance( "SELECT value FROM application_params WHERE name = 'greeting_message'"); ``` -------------------------------- ### Avoid redundant Javadoc links Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Example of an unnecessary link to the class itself within its own documentation. ```java /** * @return this {@link Builder} <-- completely unnecessary */ Builder withLimit(int limit) { ``` -------------------------------- ### Registering a Custom Codec at Runtime Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/custom_codecs/README.md Demonstrates how to register a custom codec with the CqlSession at runtime. This is useful when you need to dynamically add codecs after the session has been initialized. ```java MutableCodecRegistry registry = (MutableCodecRegistry) session.getContext().getCodecRegistry(); registry.register(myCodec); ``` -------------------------------- ### Maven Project Structure Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/integration/README.md This snippet shows the basic file structure for a Maven project using the Java driver. Ensure these files are present for a minimal setup. ```bash $ find . -type f ./pom.xml ./src/main/resources/application.conf ./src/main/resources/logback.xml ./src/main/java/Main.java ``` -------------------------------- ### Generated Schema for Polymorphic Entities Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/entities/README.md Illustrates the CQL schema generated from the polymorphic entity mapping example. ```sql CREATE TYPE point2d ("X" int, "Y" int) CREATE TYPE point3d ("X" int, "Y" int, "Z" int) CREATE TABLE rectangles (rect_id uuid PRIMARY KEY, bottom_left frozen, top_right frozen) CREATE TABLE circles (circle_id uuid PRIMARY KEY, center2d frozen, radius double) CREATE TABLE spheres (sphere_id uuid PRIMARY KEY, center3d frozen, radius double) ``` -------------------------------- ### Product DAO with ListenableFuture Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/daos/custom_types/README.md Example of a Product DAO interface using Guava's ListenableFuture for all its methods. This demonstrates the target interface when integrating custom result types. ```java import com.google.common.util.concurrent.ListenableFuture; @Dao public interface ProductDao { @Select ListenableFuture select(UUID id); @Update ListenableFuture update(Product entity); @Insert ListenableFuture insert(Product entity); @Delete ListenableFuture delete(Product entity); } ``` -------------------------------- ### Bind UDT Value to a Bound Statement Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/udts/README.md Example of binding a prepared UDT value to a BoundStatement before execution. ```java BoundStatement bs = ps.boundStatementBuilder() .setInt("pk", 1) .setString("ck1", "1") .setString("ck2", "1") .setUdtValue("v", udtValue) .build(); session.execute(bs); ``` -------------------------------- ### Transforming collections with the Stream API Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Example of using the Stream API to map and collect list elements. ```java List sizes = words.stream().map(String::length).collect(Collectors.toList()); ``` -------------------------------- ### Build Project with Maven Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md Use this Maven command to clean and package the project, skipping tests during the build process. ```bash mvn clean package -DskipTests ``` -------------------------------- ### Format License Headers with Maven Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Ensure all files have the correct license headers by running the Maven license plugin. ```bash mvn license:format ``` -------------------------------- ### Avoid redundant Javadoc Source: https://github.com/apache/cassandra-java-driver/blob/4.x/CONTRIBUTING.md Example of an unnecessary Javadoc comment that provides no additional value over the method signature. ```java /** * Returns the name. * * @return the name */ String getName(); ``` -------------------------------- ### Generate Server and Client Keystores Source: https://github.com/apache/cassandra-java-driver/blob/4.x/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md Creates the initial keystores for the server and two clients using RSA key algorithm. Ensure RSA is used as TLS 1.3 does not support DSA. ```bash $ keytool -genkeypair -keyalg RSA -alias server -keystore server.keystore -dname "CN=server" -storepass changeit -keypass changeit $ keytool -genkeypair -keyalg RSA -alias client-original -keystore client-original.keystore -dname "CN=client-original" -storepass changeit -keypass changeit $ keytool -genkeypair -keyalg RSA -alias client-alternate -keystore client-alternate.keystore -dname "CN=client-alternate" -storepass changeit -keypass changeit ``` -------------------------------- ### Example PR Title Format Source: https://github.com/apache/cassandra-java-driver/blob/4.x/mkdocs/CONTRIBUTING.md When submitting a pull request, include the JIRA key in the title for tracking purposes. ```text CASSJAVA-40: Driver testing against Java 21 ``` -------------------------------- ### Entity Property Extraction Example Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/daos/getentity/README.md The generated code for a @GetEntity method will retrieve each entity property from the source row. ```java Product product = new Product(); product.setId(row.get("id", UUID.class)); product.setDescription(row.get("description", String.class)); ... ``` -------------------------------- ### Create Client Truststore Source: https://github.com/apache/cassandra-java-driver/blob/4.x/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md Imports the server certificate into the client's truststore, enabling the client to trust the server. ```bash $ keytool -import -file server.cert -alias server -keystore client.truststore -storepass changeit ``` -------------------------------- ### Use UDT in a Table Definition Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/udts/README.md Example of creating a table 'collect_things' that uses a UDT ('type1') as a column type. ```cql CREATE TABLE ks.collect_things ( pk int, ck1 text, ck2 text, v frozen, PRIMARY KEY (pk, ck1, ck2) ); ``` -------------------------------- ### Override Default Configuration and Add a Profile Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/configuration/README.md Customize driver settings by creating an application.conf file. This example overrides the protocol version and defines a new 'slow' execution profile with a longer timeout. ```HOCON # Sample application.conf: overrides one option and adds a profile datastax-java-driver { advanced.protocol.version = V4 profiles { slow { basic.request.timeout = 10 seconds } } } ``` -------------------------------- ### Configure SSL with Driver Properties Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/ssl/README.md Use these properties in the driver configuration to set up SSL, including truststore/keystore paths, passwords, and hostname validation. ```HOCON datastax-java-driver { advanced.ssl-engine-factory { class = DefaultSslEngineFactory # This property is optional. If it is not present, the driver won't explicitly enable cipher # suites on the engine, which according to the JDK documentations results in "a minimum quality # of service". // cipher-suites = [ "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA" ] # Whether or not to require validation that the hostname of the server certificate's common # name matches the hostname of the server being connected to. If not set, defaults to true. // hostname-validation = true # The locations and passwords used to access truststore and keystore contents. # These properties are optional. If either truststore-path or keystore-path are specified, # the driver builds an SSLContext from these files. If neither option is specified, # the default SSLContext is used, which is based on system property configuration. // truststore-path = /path/to/client.truststore // truststore-password = password123 // keystore-path = /path/to/client.keystore // keystore-password = password123 # The duration between attempts to reload the keystore from the contents of the file specified # by `keystore-path`. This is mainly relevant in environments where certificates have short # lifetimes and applications are restarted infrequently, since an expired client certificate # will prevent new connections from being established until the application is restarted. // keystore-reload-interval = 30 minutes } } ``` -------------------------------- ### Asynchronous Paging with AsyncResultSet Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/paging/README.md Iterate through an AsyncResultSet asynchronously by fetching pages explicitly. This example prints each row to the console. ```java CompletionStage resultSetFuture = session.executeAsync("SELECT * FROM myTable WHERE id = 1"); // The returned stage will complete once all the rows have been printed: CompletionStage printRowsFuture = resultSetFuture.thenCompose(this::printRows); private CompletionStage printRows(AsyncResultSet resultSet) { for (Row row : resultSet.currentPage()) { System.out.println(row.getFormattedContents()); } if (resultSet.hasMorePages()) { return resultSet.fetchNextPage().thenCompose(this::printRows); } else { return CompletableFuture.completedFuture(null); } } ``` -------------------------------- ### Execute a Simple Statement Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/simple/README.md Demonstrates the basic execution of a simple statement using SimpleStatement.newInstance(). ```java SimpleStatement statement = SimpleStatement.newInstance( "SELECT value FROM application_params WHERE name = 'greeting_message'"); session.execute(statement); ``` -------------------------------- ### Create Simple Statement with Builder Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/simple/README.md Demonstrates creating a simple statement with multiple options using the builder pattern. ```java SimpleStatement statement = SimpleStatement.builder("SELECT value FROM application_params WHERE name = 'greeting_message'") .setIdempotence(true) .build(); ``` -------------------------------- ### Get MappedAsyncPagingIterable of Entities from AsyncResultSet Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/daos/getentity/README.md Use this to retrieve a MappedAsyncPagingIterable of entity instances from an AsyncResultSet. Each row is converted into an entity. ```java @GetEntity MappedAsyncPagingIterable asProducts(AsyncResultSet resultSet); ``` -------------------------------- ### Get PagingIterable of Entities from ResultSet Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/mapper/daos/getentity/README.md Use this to retrieve a PagingIterable of entity instances from a ResultSet. Each row is converted into an entity. ```java @GetEntity PagingIterable asProducts(ResultSet resultSet); ``` -------------------------------- ### Setting Per-Query Keyspace and Routing Keyspace Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/statements/per_query_keyspace/README.md Demonstrates setting a per-query keyspace using `setKeyspace()`. The `setRoutingKeyspace()` call is shown as unnecessary and will be ignored when a per-query keyspace is already set. ```java SimpleStatement statement = SimpleStatement.newInstance("SELECT * FROM foo WHERE k = 1") .setKeyspace(keyspace) .setRoutingKeyspace(keyspace); // NOT NEEDED: will be ignored ``` -------------------------------- ### Get UserDefinedType from Schema Metadata Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/udts/README.md Demonstrates fetching a UserDefinedType by its keyspace and name from the driver's schema metadata. ```java UserDefinedType udt = session.getMetadata() .getKeyspace("ks") .flatMap(ks -> ks.getUserDefinedType("type1")) .orElseThrow(() -> new IllegalArgumentException("Missing UDT definition")); ``` -------------------------------- ### Create Server Truststore Source: https://github.com/apache/cassandra-java-driver/blob/4.x/core/src/test/resources/ReloadingKeyManagerFactoryTest/README.md Imports the client certificates into the server's truststore, allowing the server to trust these clients. ```bash $ keytool -import -file client-original.cert -alias client-original -keystore server.truststore -storepass changeit $ keytool -import -file client-alternate.cert -alias client-alternate -keystore server.truststore -storepass changeit ``` -------------------------------- ### Get UserDefinedType from Prepared Statement Metadata Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/udts/README.md Shows how to obtain the UserDefinedType object from the variable definitions of a prepared statement. ```java UserDefinedType udt = (UserDefinedType) ps.getVariableDefinitions().get("v").getType(); ``` -------------------------------- ### Reading and Writing Lists of Custom Objects Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/custom_codecs/README.md Demonstrates how to read and write a CQL list as a Java List, assuming a JSON codec for Price is registered. It shows both direct and generic type token methods. ```java List prices1 = row.getList("v", Price.class); // alternative method using the generic get method with type token argument: List prices2 = row.get("v", GenericType.listOf(Price.class)); // Writing boundStatement.setList("v", prices1, Price.class); // alternative method using the generic set method with type token argument: boundStatement.set("v", prices2, GenericType.listOf(Price.class)); ``` -------------------------------- ### Retrieve All Token Ranges Source: https://github.com/apache/cassandra-java-driver/blob/4.x/manual/core/metadata/token/README.md Get all token ranges in the ring. The actual token implementation depends on the configured partitioner. ```java Set ring = tokenMap.getTokenRanges(); // Returns [Murmur3TokenRange(Murmur3Token(12), Murmur3Token(2)), // Murmur3TokenRange(Murmur3Token(2), Murmur3Token(4)), // Murmur3TokenRange(Murmur3Token(4), Murmur3Token(6)), // Murmur3TokenRange(Murmur3Token(6), Murmur3Token(8)), // Murmur3TokenRange(Murmur3Token(8), Murmur3Token(10)), // Murmur3TokenRange(Murmur3Token(10), Murmur3Token(12))] ```