### Clone and Navigate ScyllaDB Cloud Getting Started Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/csharp/README.md This command clones the ScyllaDB Cloud Getting Started repository and navigates into the C# project directory. It's the initial step for setting up the media player metrics project. ```sh git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started/csharp ``` -------------------------------- ### Install Rust and Dependencies Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-rust.md Installs Rust, Cargo, and other necessary tools for Rust development. This is a prerequisite for building Rust applications. ```shell $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install gocqlx Package for ScyllaDB Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-golang.md Installs the gocqlx package, a Go library for ScyllaDB and Cassandra, which simplifies database interactions. This is a prerequisite for connecting to and querying ScyllaDB. ```sh go get -u github.com/scylladb/gocqlx/v2 ``` -------------------------------- ### Install Bundler Gem Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Installs the bundler gem, a dependency manager for Ruby projects, using the gem command. This is a prerequisite for managing project dependencies. ```shell gem install bundler ``` -------------------------------- ### Clone and Run Go Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/go/README.md Instructions to clone the ScyllaDB Cloud getting started repository and run the Go media player project. This involves cloning the repository, navigating to the Go directory, installing dependencies, and configuring environment variables. ```bash git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started/go go get ./... ``` -------------------------------- ### Clone and Run Ruby Media Player Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/ruby/README.md This snippet shows how to clone the ScyllaDB Cloud Getting Started repository and navigate to the Ruby project directory. It then demonstrates installing project dependencies using Bundler and running the main Ruby script with example cluster connection details. ```shell git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started/ruby bundle && ruby main.rb scylla yourpassword node-0,node-1,node-2 ``` -------------------------------- ### Set up ScyllaDB Cloud Python Project Environment Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-python.md Commands to create a project directory, set up a virtual environment, and install the ScyllaDB Python driver. ```sh mkdir scylladb-cloud-python cd scylladb-cloud-python virtualenv env source env/bin/activate pip install scylla-driver ``` -------------------------------- ### Initialize New Ruby Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Creates a new directory for the media player project and initializes it with `bundle init`. This command sets up the basic project structure and a Gemfile. ```shell mkdir media_player && cd media_player && bundle init ``` -------------------------------- ### Start Elixir Interactive Shell Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-elixir.md Launches the Elixir interactive shell (iex) with the current Mix project loaded. This allows developers to test Elixir code, modules, and database interactions directly within the shell. ```shell iex -S mix ``` -------------------------------- ### Initialize Golang Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-golang.md Initializes a new Golang project using go mod. This command creates a go.mod file to manage project dependencies. ```sh go mod init scylla-cloud-getting-started/golang ``` -------------------------------- ### Clone and Run Elixir Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/elixir/README.md Clones the ScyllaDB Cloud Getting Started repository and navigates into the Elixir directory. Installs project dependencies and runs the Elixir application. Assumes Git and Elixir are installed. ```shell git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started/elixir mix deps.get && mix run ``` -------------------------------- ### Clone ScyllaDB Cloud Getting Started Repository Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/python/README.MD Clones the scylla-cloud-getting-started repository from GitHub and navigates into the project directory. This is the initial step to set up the project locally. ```shell git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started ``` -------------------------------- ### Go Driver - Connect and Query Data Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Illustrates connecting to ScyllaDB Cloud and executing a query using the Go driver (`gocqlx`). This example defines a `Song` struct to map query results and fetches data from the `media_player.playlist` table. It requires the `github.com/gocql/gocql` and `github.com/scylladb/gocqlx/v2` packages. ```go package main import ( "fmt" "time" "github.com/gocql/gocql" "github.com/scylladb/gocqlx/v2" ) type Song struct { Id string Title string Artist string Album string Created_at time.Time } func main() { cluster := gocql.NewCluster( "node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-2.aws-sa-east-1.xxx.clusters.scylla.cloud", ) cluster.Authenticator = gocql.PasswordAuthenticator{ Username: "scylla", Password: "your-password", } cluster.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("AWS_US_EAST_1") session, err := gocqlx.WrapSession(cluster.CreateSession()) if err != nil { panic("Connection fail") } song := Song{} q := session.Query("SELECT * FROM media_player.playlist", nil) if err := q.SelectRelease(&song); err != nil { panic(fmt.Sprintf("error in exec query: %v", err)) } fmt.Println(song) } ``` -------------------------------- ### JavaScript (Node.js) Driver - Connect and Query Data Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Shows how to connect to ScyllaDB Cloud and retrieve data using the `cassandra-driver` npm package. This example queries all songs from the 'media_player' keyspace and prints them to the console. Ensure the `cassandra-driver` is installed (`npm install cassandra-driver`). ```javascript const cassandra = require('cassandra-driver'); const cluster = new cassandra.Client({ contactPoints: [ "node-0.xxx.clusters.scylla.cloud", "node-1.xxx.clusters.scylla.cloud", "node-2.xxx.clusters.scylla.cloud" ], localDataCenter: 'AWS_SA_EAST_1', credentials: { username: 'scylla', password: 'your-password' }, keyspace: 'media_player' }); async function listSongs() { let results = await cluster.execute("SELECT * FROM songs"); let rows = results.rows; for (let i in rows) { console.log(rows[i]); console.log(rows[i].id.toString()); } await cluster.shutdown(); } listSongs(); ``` -------------------------------- ### Install Cassandra Driver for Node.js Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-javascript.md Installs the DataStax JavaScript Cassandra driver, which is compatible with ScyllaDB. This is the first step to interact with your ScyllaDB cluster using Node.js. ```sh $ npm install cassandra-driver $ yarn install cassandra-driver ``` -------------------------------- ### Prepare for Table Creation Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Connects to a ScyllaDB cluster and a specific keyspace ('media_player') to prepare for table creation. This snippet sets up the connection context for subsequent table operations. ```ruby # frozen_string_literal: true require 'cassandra' cluster = Cassandra.cluster( username: 'scylla', password: 'a-strong-password', hosts: [ 'node-0.aws-us-east-1.first.clusters.scylla.cloud', 'node-1.aws-us-east-1.second.clusters.scylla.cloud', 'node-2.aws-us-east-1.third.clusters.scylla.cloud' ] ) keyspace = 'media_player' table = 'playlist' session = cluster.connect(keyspace) ``` -------------------------------- ### Java Driver: Connect to ScyllaDB Cloud and Query Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Demonstrates connecting to ScyllaDB Cloud using the Java driver. This example includes data center awareness configuration and executes a simple query against the 'system.clients' table. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints( "node-0.xxx.clusters.scylla.cloud", "node-1.xxx.clusters.scylla.cloud", "node-2.xxx.clusters.scylla.cloud" ) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) .withAuthProvider(new PlainTextAuthProvider("scylla", "your-password")) .build(); Session session = cluster.connect(); ResultSet result = session.execute("SELECT * FROM system.clients LIMIT 10"); System.out.println(result); } } ``` -------------------------------- ### Install AWS SDK for PHP using Composer Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/alternator/build-with-php.md This command installs the AWS SDK for PHP package using Composer, a dependency manager for PHP. This is a prerequisite for using the SDK in your project. ```shell composer require aws/aws-sdk-php ``` -------------------------------- ### Query ScyllaDB Data using CQLSH Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md This example shows a CQLSH command to query all columns from the 'songs' table, filtered by a specific 'id'. It illustrates how data is returned after an update operation, highlighting which fields were modified. ```default scylla@cqlsh:media_player> select * from songs where id = 1; id | updated_at | album | artist | created_at | title ---+---------------------------------+-------------+--------+---------------------------------+---------------------------- 1 | 2023-03-02 22:00:00.000000+0000 | Smithereens | Joji | 2023-03-02 22:00:00.000000+0000 | Glimpse of Us 1 | 2023-03-02 23:10:00.000000+0000 | null | null | null | Glimpse of US - Inutilismo ``` -------------------------------- ### Install Python AWS SDK (boto3) Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/alternator/build-with-python.md Installs or upgrades the boto3 library, which is the Python AWS SDK used to interact with ScyllaDB Alternator. This is a prerequisite for running the subsequent Python code examples. ```shell sudo pip install --upgrade boto3 ``` -------------------------------- ### Create New Rust Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-rust.md Initializes a new Rust project using Cargo, the Rust build system and package manager. This command creates a basic project structure. ```sh cargo new media_player ``` -------------------------------- ### Rust Driver: Insert Data with Prepared Statements Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Illustrates how to insert data into ScyllaDB using prepared statements for improved performance. This example inserts song data into a 'songs' table after preparing the insert statement. ```rust use anyhow::Result; use chrono::Utc; use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use std::str::FromStr; use std::time::Duration; use uuid::Uuid; #[tokio::main] async fn main() -> Result<()> { let session: Session = SessionBuilder::new() .known_nodes(&[ "node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-2.aws-sa-east-1.xxx.clusters.scylla.cloud", ]) .connection_timeout(Duration::from_secs(5)) .user("scylla", "your-password") .build() .await .unwrap(); session.use_keyspace("media_player", false).await?; let now = Utc::now(); let song_list = vec![ (Uuid::new_v4(), "Stairway to Heaven", "Led Zeppelin IV", "Led Zeppelin", now), (Uuid::from_str("d754f8d5-e037-4898-af75-44587b9cc424").unwrap(), "Glimpse of Us", "Smithereens", "Joji", now), ]; let insert_query = "INSERT INTO songs (id,title,album,artist,created_at) VALUES (?,?,?,?,?)"; let prepared = session.prepare(insert_query).await?; for song in song_list { session.execute_unpaged(&prepared, song).await?; println!("Inserting Track: {}", song.1); } Ok(()) } ``` -------------------------------- ### Create ScyllaDB Keyspace Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Connects to a ScyllaDB cluster and creates a new keyspace named 'media_player' if it doesn't already exist. It uses NetworkTopologyStrategy for replication. The script then reconnects to the cluster using the newly created keyspace. ```ruby # frozen_string_literal: true require 'cassandra' cluster = Cassandra.cluster( username: 'scylla', password: 'a-strong-password', hosts: [ 'node-0.aws-us-east-1.first.clusters.scylla.cloud', 'node-1.aws-us-east-1.second.clusters.scylla.cloud', 'node-2.aws-us-east-1.third.clusters.scylla.cloud' ] ) keyspace = 'media_player' session = cluster.connect # Verify if the Keyspace already exists in your Cluster has_keyspace = session.execute_async('select keyspace_name from system_schema.keyspaces WHERE keyspace_name=?', arguments: [keyspace]).join.rows.size if has_keyspace.zero? new_keyspace_query = <<~SQL CREATE KEYSPACE #{keyspace} WITH replication = { 'class': 'NetworkTopologyStrategy', 'replication_factor': '3' } AND durable_writes = true SQL session.execute_async(new_keyspace_query).join puts "Keyspace #{keyspace} created!" else puts "Keyspace #{keyspace} already created!" end # Reconnecting to the cluster with the correct keyspace session = cluster.connect(keyspace) ``` -------------------------------- ### Create ScyllaDB Keyspace Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/design-and-data-model.md Defines a new keyspace named 'prod_media_player' with a NetworkTopologyStrategy and a replication factor of 3. This is a fundamental step before creating tables in ScyllaDB. ```cql CREATE KEYSPACE prod_media_player WITH replication = {'class': 'NetworkTopologyStrategy', 'replication_factor': '3'} AND durable_writes = true; ``` -------------------------------- ### Connect to ScyllaDB Cluster Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Establishes a connection to a ScyllaDB cluster using the `cassandra-driver` gem. It requires username, password, and a list of cluster host addresses. Ensure your IP is allowed. ```ruby # frozen_string_literal: true require 'cassandra' cluster = Cassandra.cluster( username: 'scylla', password: 'a-very-secure-password', hosts: [ 'node-0.aws-sa-east-1.xxx.clusters.scylla.cloud', 'node-1.aws-sa-east-1.xxx.clusters.scylla.cloud', 'node-2.aws-sa-east-1.xxx.clusters.scylla.cloud' ] ) ``` -------------------------------- ### Execute a Query on ScyllaDB with Java Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md This Java snippet shows how to execute a simple SELECT query against a ScyllaDB cluster after establishing a connection. It retrieves and prints the result set. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints( "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud" ) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) // your local data center .withAuthProvider(new PlainTextAuthProvider("scylla", "your-awesome-password")) .build(); Session session = cluster.connect(); ResultSet result = session.execute("SELECT * FROM system.clients LIMIT 10"); System.out.println(result); } } ``` -------------------------------- ### Execute Queries with ScyllaDB Node.js Driver Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-javascript.md Demonstrates how to execute CQL queries against your ScyllaDB cluster using the Node.js driver. It shows connecting to the cluster and running a SELECT query, then logging the results. ```js const cluster = new cassandra.Client({ contactPoints: ["your-node-url.clusters.scylla.cloud", "your-node-url.clusters.scylla.cloud", ...], localDataCenter: 'your-data-center', // Eg: AWS_SA_EAST_1 credentials: {username: 'scylla', password: 'your-awesome-password'} }) const results = await cluster.execute('SELECT * FROM system.clients LIMIT 10') console.log(results); results.rows.forEach(row => console.log(JSON.stringify(row))) ``` -------------------------------- ### Configure Project Dependencies in Cargo.toml Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-rust.md Defines the project's dependencies in the `Cargo.toml` file. It includes ScyllaDB driver, UUID generation, async runtime, error handling, and date/time libraries. ```toml [package] name = "media_player" version = "0.1.0" edition = "2021" [dependencies] scylla = { version = "1.0", features = ["chrono-04"] } uuid = {version = "0.8", features = ["v4"]} tokio = { version = "1.17.0", features = ["full"] } anyhow = "1.0.70" chrono = "0.4.24" utures = "0.3.28" ``` -------------------------------- ### Create ScyllaDB Keyspace in Go Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-golang.md Creates a new keyspace named 'media_player' in ScyllaDB if it doesn't already exist. This operation configures replication strategy and durable writes for the keyspace. It requires an active session to the cluster. ```go cluster := gocql.NewCluster("node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud","node-2.aws-sa-east-1.xxx.clusters.scylla.cloud") cluster.Authenticator = gocql.PasswordAuthenticator{Username: "Canhassi", Password: "password123"} cluster.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("AWS_US_EAST_1") session, err := gocqlx.WrapSession(cluster.CreateSession()) if err != nil { panic("Connection fail") } session.Query("CREATE KEYSPACE IF NOT EXISTS media_player WITH replication = {'class': 'NetworkTopologyStrategy', 'replication_factor': '3'} AND durable_writes = true;", nil).Exec() ``` -------------------------------- ### Connect to ScyllaDB Cloud Cluster with Java Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md This Java code demonstrates how to establish a connection to a ScyllaDB Cloud cluster using the DataStax Java driver. It configures contact points, load balancing policy, and authentication. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.Session; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints("your-node-url.scylla.cloud", "your-node-url.clusters.scylla.cloud", "your-node-url.clusters.scylla.cloud") .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) // your local data center .withAuthProvider(new PlainTextAuthProvider("scylla", "your-awesome-password")) .build(); Session session = cluster.connect(); } } ``` -------------------------------- ### Create a ScyllaDB Keyspace with Java Schema Builder Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md This Java code utilizes the ScyllaDB driver's schema builder to create a new keyspace named 'media_player'. It configures replication strategy and durable writes. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createKeyspace; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints( "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud" ) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) // your local data center .withAuthProvider(new PlainTextAuthProvider("scylla", "your-awesome-password")) .build(); Session session = cluster.connect(); String createKeyspaceQuery = createKeyspace("media_player") .ifNotExists() .with() .replication(ImmutableMap.of("class", "NetworkTopologyStrategy", "replication_factor", 3)) .durableWrites(true) .getQueryString(); session.execute(createKeyspaceQuery) } } ``` -------------------------------- ### Add ScyllaDB Dependencies to Mix Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-elixir.md Defines project dependencies in the `mix.exs` file, including the 'decimal' library for arbitrary precision arithmetic and the 'xandra' driver for ScyllaDB/Cassandra interaction. These dependencies are crucial for connecting to and querying the database. ```elixir defp deps do [ {:decimal, "~> 1.0"}, {:xandra, "~> 0.14"} ] end ``` -------------------------------- ### Clone and Install PHP Project Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/alternator/php/README.MD Clones the ScyllaDB Cloud getting started repository and installs project dependencies using Composer. This is the initial setup step for the PHP media player project. ```shell git clone https://github.com/scylladb/scylla-cloud-getting-started.git cd scylla-cloud-getting-started/alternator/php composer install ``` -------------------------------- ### Alternator (DynamoDB API) - Python Example Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Illustrates how to use ScyllaDB's Alternator, which provides a DynamoDB-compatible API, with Python's boto3 library. This example shows creating a table, inserting an item, and scanning for items. ```python import boto3 import uuid from datetime import datetime alternator = boto3.resource( 'dynamodb', endpoint_url='http://localhost:8000', # Or your ScyllaDB Cloud Alternator endpoint region_name='None', aws_access_key_id='None', aws_secret_access_key='None' ) # Create table table = alternator.create_table( TableName="songs", KeySchema=[ {'AttributeName': 'id', 'KeyType': 'HASH'}, {'AttributeName': 'created_at', 'KeyType': 'RANGE'}, ], AttributeDefinitions=[ {'AttributeName': 'id', 'AttributeType': 'S'}, {'AttributeName': 'created_at', 'AttributeType': 'S'}, ], ProvisionedThroughput={'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10} ) table.wait_until_exists() # Insert item table.put_item(Item={ 'id': str(uuid.uuid4()), 'created_at': str(datetime.now()), 'title': 'Song 1', 'album': 'Album 1', 'artist': 'Artist Name', }) # List items songs = table.scan() for song in songs['Items']: print(f"Title: {song['title']} | Album: {song['album']}") ``` -------------------------------- ### Create New Elixir Project with Mix Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-elixir.md Initializes a new Elixir project named 'media_player' using the Mix build tool. This command sets up the basic project structure and configuration files required for an Elixir application. ```shell mix new media_player ``` -------------------------------- ### Add Elixir UUID Dependency Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-elixir.md This snippet shows how to add the `elixir_uuid` dependency to your `mix.exs` file. This dependency is necessary for generating UUIDs, which are used as primary keys in this example. After adding the dependency, run `mix deps.get` to fetch it. ```elixir {:elixir_uuid, "~> 1.2"} ``` -------------------------------- ### Execute Queries and Handle Results in Python with ScyllaDB Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-python.md Demonstrates how to connect to ScyllaDB, execute a query to retrieve system client information, and iterate over the results. Supports both synchronous and asynchronous execution. ```python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider cluster = Cluster( contact_points=[ "your-node-url-1.clusters.scylla.cloud", "your-node-url-2.clusters.scylla.cloud", "your-node-url-3.clusters.scylla.cloud", ], auth_provider=PlainTextAuthProvider(username='scylla', password='your-awesome-password') ) session = cluster.connect() results = session.execute('SELECT * FROM system.clients LIMIT 10') for item in results: print(item) print(item.address) ``` -------------------------------- ### Set Up Python Virtual Environment and Install Driver Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/python/README.MD Creates a Python virtual environment named 'env' and activates it. It then installs the 'scylla-driver' package, which is necessary for interacting with ScyllaDB. ```shell virtualenv env source env/bin/activate pip install scylla-driver ``` -------------------------------- ### Delete Data in ScyllaDB using Java Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md Provides a Java code example for deleting data from ScyllaDB Cloud. This snippet uses the DataStax Java driver to connect to a ScyllaDB cluster and execute a prepared DELETE statement to remove a row by its ID. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import java.util.Date; import java.util.Scanner; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints( "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud" ) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) // your local data center .withAuthProvider(new PlainTextAuthProvider("scylla", "your-awesome-password")) .build(); Session session = cluster.connect(); PreparedStatement statement = session.prepare( "DELETE FROM songs where id = ?" ); BoundStatement bound = statement.bind() .setLong(0, 1); session.execute(bound); } } ``` -------------------------------- ### Connect to ScyllaDB Cloud Cluster (Python) Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Establishes a connection to a ScyllaDB Cloud cluster using the Python Cassandra driver. It requires cluster contact points and authentication credentials. The example demonstrates executing a simple query to verify the connection. ```python from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider cluster = Cluster( contact_points=[ "node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-2.aws-sa-east-1.xxx.clusters.scylla.cloud", ], auth_provider=PlainTextAuthProvider(username='scylla', password='your-password') ) session = cluster.connect() results = session.execute('SELECT * FROM system.clients LIMIT 10') for item in results: print(item.address) ``` -------------------------------- ### Create a Keyspace in ScyllaDB Cloud with Python Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-python.md Python code to create a new keyspace (database) in ScyllaDB Cloud with a specified replication factor. This involves connecting to the cluster and executing a CQL CREATE KEYSPACE statement. ```python from cassandra.cluster import Cluster from datetime import datetime from cassandra.auth import PlainTextAuthProvider cluster = Cluster( contact_points=[ "your-node-url-1.clusters.scylla.cloud", "your-node-url-2.clusters.scylla.cloud", "your-node-url-3.clusters.scylla.cloud", ], auth_provider=PlainTextAuthProvider(username='scylla', password='your-awesome-password') ) session = cluster.connect() keyspaceName = "media_player" replicationFactor = 3 session.execute( """ CREATE KEYSPACE {} WITH replication = {{'class': 'NetworkTopologyStrategy', 'replication_factor': '{}'}} AND durable_writes = true; """.format(keyspaceName, replicationFactor) ) session.set_keyspace('media_player') ``` -------------------------------- ### JavaScript (Node.js) Driver - Insert Multiple Songs Source: https://context7.com/scylladb/scylla-cloud-getting-started/llms.txt Demonstrates inserting multiple song records into ScyllaDB using the Node.js driver. It defines a list of songs and iterates through them, executing an INSERT statement for each. This example uses `cassandra.types.Uuid.random()` for generating unique IDs. Requires the `cassandra-driver` package. ```javascript const cassandra = require('cassandra-driver'); async function insertSongs() { const cluster = new cassandra.Client({ contactPoints: ["node-0.xxx.clusters.scylla.cloud", "node-1.xxx.clusters.scylla.cloud"], localDataCenter: 'AWS_SA_EAST_1', credentials: { username: 'scylla', password: 'your-password' }, keyspace: 'media_player' }); let songList = [ { id: cassandra.types.Uuid.random(), title: 'Stairway to Heaven', album: 'Led Zeppelin IV', artist: 'Led Zeppelin', createdAt: '2023-03-02 22:00:00', }, { id: 'd754f8d5-e037-4898-af75-44587b9cc424', title: 'Glimpse of Us', album: 'Smithereens', artist: 'Joji', createdAt: '2023-03-02 22:00:00', }, ]; const newSongQuery = (song) => { return `INSERT INTO songs (id, title, album, artist, created_at)` `VALUES (${song.id}, '${song.title}', '${song.album}', '${song.artist}', '${song.createdAt}')`; }; for (let i in songList) { await cluster.execute(newSongQuery(songList[i])); } await cluster.shutdown(); } insertSongs(); ``` -------------------------------- ### Create a Table in ScyllaDB Cloud with Python Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-python.md Python code to create a 'songs' table within a specified keyspace in ScyllaDB Cloud. The table is designed to store song details including ID, title, album, artist, and creation timestamp. ```python from cassandra.cluster import Cluster from datetime import datetime from cassandra.auth import PlainTextAuthProvider cluster = Cluster( contact_points=[ "your-node-url-1.clusters.scylla.cloud", "your-node-url-2.clusters.scylla.cloud", "your-node-url-3.clusters.scylla.cloud", ], auth_provider=PlainTextAuthProvider(username='scylla', password='your-awesome-password') ) session = cluster.connect('media_player') tableQuery = """ CREATE TABLE songs ( id uuid, title text, album text, artist text, created_at timestamp, PRIMARY KEY (id, created_at) ) " session.execute(tableQuery) ``` -------------------------------- ### Define Gemfile for Cassandra Driver Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-ruby.md Specifies the `cassandra-driver` gem with a version constraint in the `Gemfile`. This file is used by Bundler to manage project dependencies. ```ruby # frozen_string_literal: true source 'https://rubygems.org' gem 'cassandra-driver', '~> 3.2' ``` -------------------------------- ### Create a Keyspace in ScyllaDB using JavaScript Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-javascript.md Defines and executes a CQL query to create a new keyspace in ScyllaDB. This function takes a keyspace name and replication factor, then connects to the cluster to run the creation command. ```js async function runKeyspace () { const cluster = new cassandra.Client({ contactPoints: ["your-node-url.clusters.scylla.cloud", "your-node-url.clusters.scylla.cloud", ...], localDataCenter: 'your-data-center', // Eg: AWS_SA_EAST_1 credentials: {username: 'scylla', password: 'your-awesome-password'}, }) const newKeyspace = (keyspaceName, rf) => ` CREATE KEYSPACE ${keyspaceName} WITH replication = {'class': 'NetworkTopologyStrategy', 'replication_factor': '${rf}'} AND durable_writes = true; `; await cluster.execute(newKeyspace('media_player', 3)) await cluster.shutdown() } runKeyspace(); ``` -------------------------------- ### Connect to ScyllaDB Cloud Cluster in Go Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-golang.md Establishes a connection to a ScyllaDB Cloud cluster using the gocqlx library. It configures cluster nodes, authentication, and host selection policy. Ensure your IP is whitelisted in ScyllaDB Cloud. ```go func main() { cluster := gocql.NewCluster("node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud","node-2.aws-sa-east-1.xxx.clusters.scylla.cloud") cluster.Authenticator = gocql.PasswordAuthenticator{Username: "Canhassi", Password: "password123"} cluster.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("AWS_US_EAST_1") session, err := gocqlx.WrapSession(cluster.CreateSession()) if err != nil { panic("Connection fail") } } ``` -------------------------------- ### Create Table in ScyllaDB Cloud using C# Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-csharp.md This C# code snippet demonstrates how to connect to ScyllaDB Cloud and create a new table within a specified keyspace. It checks if the table already exists before attempting creation. Requires the Cassandra C# driver. ```csharp using Cassandra; using System; using System.Text; using System.Linq; namespace Program; public class Program { static void Main(string[] args) { var cluster = Cluster.Builder() .AddContactPoints("node-0.aws-sa-east-1.xxx.clusters.scylla.cloud") .AddContactPoints("node-1.aws-sa-east-1.xxx.clusters.scylla.cloud") .AddContactPoints("node-2.aws-sa-east-1.xxx.clusters.scylla.cloud") .WithCredentials("scylla", "a-very-secure-password") .Build(); string keyspace = "media_player"; string table = "playlist"; var session = cluster.Connect(keyspace); var ps = session.Prepare("select keyspace_name, table_name from system_schema.tables where keyspace_name = ? AND table_name = ?"); var statement = ps.Bind(keyspace, table); var result = session.Execute(statement); var rows = result .GetRows() .ToList(); if(rows.Count == 0) { StringBuilder sb = new(); sb.Append($"CREATE TABLE {keyspace}.{table} (id uuid, title text, album text, artist text, created_at timestamp, PRIMARY KEY(id, created_at));"); session.Execute(sb.ToString()); Console.WriteLine("Table created!"); } else { Console.WriteLine("Table already created!"); } } } ``` -------------------------------- ### Run ScyllaDB Cloud Media Player Metrics Application Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/csharp/README.md This command compiles and runs the ScyllaDB Cloud Media Player Metrics application. It requires user credentials and node information as arguments. Ensure you replace the placeholder variables with your actual cluster details. ```sh dotnet run youruser yourpassword node-0 node-1 node-2 ``` -------------------------------- ### Connect to ScyllaDB Cluster in Rust Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-rust.md Establishes a connection to a ScyllaDB cluster using the Rust driver. It configures known nodes, connection timeout, and authentication credentials. ```rust use anyhow::Result; use scylla::client::session::Session; use scylla::client::session_builder::SessionBuilder; use std::time::Duration; #[tokio::main] async fn main() -> Result<()> { let session: Session = SessionBuilder::new() .known_nodes(&[ "node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-2.aws-sa-east-1.xxx.clusters.scylla.cloud", ]) .connection_timeout(Duration::from_secs(30)) .user("scylla", "your-awesome-password") .build() .await .unwrap(); Ok(()) } ``` -------------------------------- ### Delete Data in ScyllaDB (SQL) Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-python.md Demonstrates SQL syntax for deleting data in ScyllaDB. Includes examples for deleting a single row and a specific column from a table. ```sql // Deletes a single row DELETE FROM songs WHERE id = d754f8d5-e037-4898-af75-44587b9cc424; // Deletes a whole column DELETE artist FROM songs WHERE id = d754f8d5-e037-4898-af75-44587b9cc424; ``` -------------------------------- ### Create ScyllaDB Table in Go Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-golang.md Creates a 'playlist' table within the 'media_player' keyspace if it does not exist. The table includes columns for song details and uses a composite primary key with clustering order. This requires an active ScyllaDB session. ```go cluster := gocql.NewCluster("node-0.aws-sa-east-1.xxx.clusters.scylla.cloud", "node-1.aws-sa-east-1.xxx.clusters.scylla.cloud","node-2.aws-sa-east-1.xxx.clusters.scylla.cloud") cluster.Authenticator = gocql.PasswordAuthenticator{Username: "Canhassi", Password: "password123"} cluster.PoolConfig.HostSelectionPolicy = gocql.DCAwareRoundRobinPolicy("AWS_US_EAST_1") session, err := gocqlx.WrapSession(cluster.CreateSession()) if err != nil { panic("Connection fail") } session.Query("CREATE TABLE IF NOT EXISTS media_player.playlist (id uuid,title text,album text,artist text,created_at timestamp,PRIMARY KEY (id, created_at)) WITH CLUSTERING ORDER BY (created_at DESC)", nil).Exec() ``` -------------------------------- ### Create Table in ScyllaDB Cloud using Java Source: https://github.com/scylladb/scylla-cloud-getting-started/blob/main/docs/source/build-with-java.md This snippet demonstrates how to create a 'songs' table within the 'media_player' keyspace in ScyllaDB Cloud. It uses the DataStax Java driver and SchemaBuilder to define the table schema, including partition and clustering keys, and columns. Ensure you have the DataStax Java driver dependency and replace placeholder connection details with your actual ScyllaDB Cloud cluster information. ```java import com.datastax.driver.core.Cluster; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.PlainTextAuthProvider; import com.datastax.driver.core.policies.DCAwareRoundRobinPolicy; import static com.datastax.driver.core.schemabuilder.SchemaBuilder.createTable; class Main { public static void main(String[] args) { Cluster cluster = Cluster.builder() .addContactPoints( "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud", "your-node-url.7207ca5a8fdc45f2b03f.clusters.scylla.cloud" ) .withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("AWS_US_EAST_1").build()) // your local data center .withAuthProvider(new PlainTextAuthProvider("scylla", "your-awesome-password")) .build(); Session session = cluster.connect(); String createTableQuery = createTable("media_player", "songs") .ifNotExists() .addPartitionKey("id", DataType.bigint()) .addClusteringColumn("updated_at", DataType.timestamp()) .addColumn("title", DataType.text()) .addColumn("album", DataType.text()) .addColumn("artist", DataType.text()) .addColumn("created_at", DataType.timestamp()) .getQueryString() session.execute(createTableQuery) } } ```