Cassandra – Create Table

Cassandra – Create Table ”; Previous Next Creating a Table You can create a table using the command CREATE TABLE. Given below is the syntax for creating a table. Syntax CREATE (TABLE | COLUMNFAMILY) <tablename> (”<column-definition>” , ”<column-definition>”) (WITH <option> AND <option>) Defining a Column You can define a column as shown below. column name1 data type, column name2 data type, example: age int, name text Primary Key The primary key is a column that is used to uniquely identify a row. Therefore,defining a primary key is mandatory while creating a table. A primary key is made of one or more columns of a table. You can define a primary key of a table as shown below. CREATE TABLE tablename( column1 name datatype PRIMARYKEY, column2 name data type, column3 name data type. ) or CREATE TABLE tablename( column1 name datatype PRIMARYKEY, column2 name data type, column3 name data type, PRIMARY KEY (column1) ) Example Given below is an example to create a table in Cassandra using cqlsh. Here we are − Using the keyspace tutorialspoint Creating a table named emp It will have details such as employee name, id, city, salary, and phone number. Employee id is the primary key. cqlsh> USE tutorialspoint; cqlsh:tutorialspoint>; CREATE TABLE emp( emp_id int PRIMARY KEY, emp_name text, emp_city text, emp_sal varint, emp_phone varint ); Verification The select statement will give you the schema. Verify the table using the select statement as shown below. cqlsh:tutorialspoint> select * from emp; emp_id | emp_city | emp_name | emp_phone | emp_sal ——–+———-+———-+———–+——— (0 rows) Here you can observe the table created with the given columns. Since we have deleted the keyspace tutorialspoint, you will not find it in the keyspaces list. Creating a Table using Java API You can create a table using the execute() method of Session class. Follow the steps given below to create a table using Java API. Step1: Create a Cluster Object First of all, create an instance of the Cluster.builder class of com.datastax.driver.core package as shown below. //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint( “127.0.0.1” ); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object. //Building a cluster Cluster cluster = builder.build(); You can build a cluster object using a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build(); Step 2: Create a Session Object Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the keyspace name in string format to this method as shown below. Session session = cluster.connect(“ Your keyspace name ” ); Here we are using the keyspace named tp. Therefore, create the session object as shown below. Session session = cluster.connect(“ tp” ); Step 3: Execute Query You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In the following example, we are creating a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below. //Query String query = “CREATE TABLE emp(emp_id int PRIMARY KEY, ” + “emp_name text, ” + “emp_city text, ” + “emp_sal varint, ” + “emp_phone varint );”; session.execute(query); Given below is the complete program to create and use a keyspace in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Create_Table { public static void main(String args[]){ //Query String query = “CREATE TABLE emp(emp_id int PRIMARY KEY, ” + “emp_name text, ” + “emp_city text, ” + “emp_sal varint, ” + “emp_phone varint );”; //Creating Cluster object Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build(); //Creating Session object Session session = cluster.connect(“tp”); //Executing the query session.execute(query); System.out.println(“Table created”); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Create_Table.java $java Create_Table Under normal conditions, it should produce the following output − Table created Print Page Previous Next Advertisements ”;

Cassandra – Update Data

Cassandra – Update Data ”; Previous Next Updating Data in a Table UPDATE is the command used to update data in a table. The following keywords are used while updating data in a table − Where − This clause is used to select the row to be updated. Set − Set the value using this keyword. Must − Includes all the columns composing the primary key. While updating rows, if a given row is unavailable, then UPDATE creates a fresh row. Given below is the syntax of UPDATE command − UPDATE <tablename> SET <column name> = <new value> <column name> = <value>…. WHERE <condition> Example Assume there is a table named emp. This table stores the details of employees of a certain company, and it has the following details − emp_id emp_name emp_city emp_phone emp_sal 1 ram Hyderabad 9848022338 50000 2 robin Hyderabad 9848022339 40000 3 rahman Chennai 9848022330 45000 Let us now update emp_city of robin to Delhi, and his salary to 50000. Given below is the query to perform the required updates. cqlsh:tutorialspoint> UPDATE emp SET emp_city=”Delhi”,emp_sal=50000 WHERE emp_id=2; Verification Use SELECT statement to verify whether the data has been updated or not. If you verify the emp table using SELECT statement, it will produce the following output. cqlsh:tutorialspoint> select * from emp; emp_id | emp_city | emp_name | emp_phone | emp_sal ——–+———–+———-+————+——— 1 | Hyderabad | ram | 9848022338 | 50000 2 | Delhi | robin | 9848022339 | 50000 3 | Chennai | rahman | 9848022330 | 45000 (3 rows) Here you can observe the table data has got updated. Updating Data using Java API You can update data in a table using the execute() method of Session class. Follow the steps given below to update data in a table using Java API. Step1: Create a Cluster Object Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below. //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint(“127.0.0.1”); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. Use the following code to create the cluster object. //Building a cluster Cluster cluster = builder.build(); You can build the cluster object using a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1″).build(); Step 2: Create a Session Object Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below. Session session = cluster.connect(“ Your keyspace name”); Here we are using the KeySpace named tp. Therefore, create the session object as shown below. Session session = cluster.connect(“tp”); Step 3: Execute Query You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In the following example, we are updating the emp table. You have to store the query in a string variable and pass it to the execute() method as shown below: String query = “ UPDATE emp SET emp_city=”Delhi”,emp_sal=50000 WHERE emp_id = 2;” ; Given below is the complete program to update data in a table using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Update_Data { public static void main(String args[]){ //query String query = ” UPDATE emp SET emp_city=”Delhi”,emp_sal=50000″ //Creating Cluster object Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build(); //Creating Session object Session session = cluster.connect(“tp”); //Executing the query session.execute(query); System.out.println(“Data updated”); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Update_Data.java $java Update_Data Under normal conditions, it should produce the following output − Data updated Print Page Previous Next Advertisements ”;

Cassandra – Architecture

Cassandra – Architecture ”; Previous Next The design goal of Cassandra is to handle big data workloads across multiple nodes without any single point of failure. Cassandra has peer-to-peer distributed system across its nodes, and data is distributed among all the nodes in a cluster. All the nodes in a cluster play the same role. Each node is independent and at the same time interconnected to other nodes. Each node in a cluster can accept read and write requests, regardless of where the data is actually located in the cluster. When a node goes down, read/write requests can be served from other nodes in the network. Data Replication in Cassandra In Cassandra, one or more of the nodes in a cluster act as replicas for a given piece of data. If it is detected that some of the nodes responded with an out-of-date value, Cassandra will return the most recent value to the client. After returning the most recent value, Cassandra performs a read repair in the background to update the stale values. The following figure shows a schematic view of how Cassandra uses data replication among the nodes in a cluster to ensure no single point of failure. Note − Cassandra uses the Gossip Protocol in the background to allow the nodes to communicate with each other and detect any faulty nodes in the cluster. Components of Cassandra The key components of Cassandra are as follows − Node − It is the place where data is stored. Data center − It is a collection of related nodes. Cluster − A cluster is a component that contains one or more data centers. Commit log − The commit log is a crash-recovery mechanism in Cassandra. Every write operation is written to the commit log. Mem-table − A mem-table is a memory-resident data structure. After commit log, the data will be written to the mem-table. Sometimes, for a single-column family, there will be multiple mem-tables. SSTable − It is a disk file to which the data is flushed from the mem-table when its contents reach a threshold value. Bloom filter − These are nothing but quick, nondeterministic, algorithms for testing whether an element is a member of a set. It is a special kind of cache. Bloom filters are accessed after every query. Cassandra Query Language Users can access Cassandra through its nodes using Cassandra Query Language (CQL). CQL treats the database (Keyspace) as a container of tables. Programmers use cqlsh: a prompt to work with CQL or separate application language drivers. Clients approach any of the nodes for their read-write operations. That node (coordinator) plays a proxy between the client and the nodes holding the data. Write Operations Every write activity of nodes is captured by the commit logs written in the nodes. Later the data will be captured and stored in the mem-table. Whenever the mem-table is full, data will be written into the SStable data file. All writes are automatically partitioned and replicated throughout the cluster. Cassandra periodically consolidates the SSTables, discarding unnecessary data. Read Operations During read operations, Cassandra gets values from the mem-table and checks the bloom filter to find the appropriate SSTable that holds the required data. Print Page Previous Next Advertisements ”;

Cassandra – Referenced Api

Cassandra – Referenced Api ”; Previous Next This chapter covers all the important classes in Cassandra. Cluster This class is the main entry point of the driver. It belongs to com.datastax.driver.core package. Methods S. No. Methods and Description 1 Session connect() It creates a new session on the current cluster and initializes it. 2 void close() It is used to close the cluster instance. 3 static Cluster.Builder builder() It is used to create a new Cluster.Builder instance. Cluster.Builder This class is used to instantiate the Cluster.Builder class. Methods S. No Methods and Description 1 Cluster.Builder addContactPoint(String address) This method adds a contact point to cluster. 2 Cluster build() This method builds the cluster with the given contact points. Session This interface holds the connections to Cassandra cluster. Using this interface, you can execute CQL queries. It belongs to com.datastax.driver.core package. Methods S. No. Methods and Description 1 void close() This method is used to close the current session instance. 2 ResultSet execute(Statement statement) This method is used to execute a query. It requires a statement object. 3 ResultSet execute(String query) This method is used to execute a query. It requires a query in the form of a String object. 4 PreparedStatement prepare(RegularStatement statement) This method prepares the provided query. The query is to be provided in the form of a Statement. 5 PreparedStatement prepare(String query) This method prepares the provided query. The query is to be provided in the form of a String. Print Page Previous Next Advertisements ”;

Cassandra – Home

Cassandra Tutorial PDF Version Quick Guide Resources Job Search Discussion Cassandra is a distributed database from Apache that is highly scalable and designed to manage very large amounts of structured data. It provides high availability with no single point of failure. The tutorial starts off with a basic introduction of Cassandra followed by its architecture, installation, and important classes and interfaces. Thereafter, it proceeds to cover how to perform operations such as create, alter, update, and delete on keyspaces, tables, and indexes using CQLSH as well as Java API. The tutorial also has dedicated chapters to explain the data types and collections available in CQL and how to make use of user-defined data types. Audience This tutorial will be extremely useful for software professionals in particular who aspire to learn the ropes of Cassandra and implement it in practice. Prerequisites It is an elementary tutorial and you can easily understand the concepts explained here with a basic knowledge of Java programming. However, it will help if you have some prior exposure to database concepts and any of the Linux flavors. Print Page Previous Next Advertisements ”;

Cassandra – Drop Table

Cassandra – Drop Table ”; Previous Next Dropping a Table You can drop a table using the command Drop Table. Its syntax is as follows − Syntax DROP TABLE <tablename> Example The following code drops an existing table from a KeySpace. cqlsh:tutorialspoint> DROP TABLE emp; Verification Use the Describe command to verify whether the table is deleted or not. Since the emp table has been deleted, you will not find it in the column families list. cqlsh:tutorialspoint> DESCRIBE COLUMNFAMILIES; employee Deleting a Table using Java API You can delete a table using the execute() method of Session class. Follow the steps given below to delete a table using Java API. Step1: Create a Cluster Object First of all, create an instance of Cluster.builder class of com.datastax.driver.core package as shown below − //Creating Cluster.Builder object Cluster.Builder builder1 = Cluster.builder(); Add a contact point (IP address of the node) using addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder. //Adding contact point to the Cluster.Builder object Cluster.Builder builder2 = build.addContactPoint( “127.0.0.1” ); Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. The following code shows how to create a cluster object. //Building a cluster Cluster cluster = builder.build(); You can build a cluster object using a single line of code as shown below. Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build(); Step 2: Create a Session Object Create an instance of Session object using the connect() method of Cluster class as shown below. Session session = cluster.connect( ); This method creates a new session and initializes it. If you already have a keyspace, you can set it to the existing one by passing the KeySpace name in string format to this method as shown below. Session session = cluster.connect(“Your keyspace name”); Here we are using the keyspace named tp. Therefore, create the session object as shown below. Session session = cluster.connect(“tp”); Step 3: Execute Query You can execute CQL queries using execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh. In the following example, we are deleting a table named emp. You have to store the query in a string variable and pass it to the execute() method as shown below. // Query String query = “DROP TABLE emp1;”; session.execute(query); Given below is the complete program to drop a table in Cassandra using Java API. import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; public class Drop_Table { public static void main(String args[]){ //Query String query = “DROP TABLE emp1;”; Cluster cluster = Cluster.builder().addContactPoint(“127.0.0.1”).build(); //Creating Session object Session session = cluster.connect(“tp”); //Executing the query session.execute(query); System.out.println(“Table dropped”); } } Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below. $javac Drop_Table.java $java Drop_Table Under normal conditions, it should produce the following output − Table dropped Print Page Previous Next Advertisements ”;

Cassandra – Cqlsh

Cassandra – Cqlsh This chapter introduces the Cassandra query language shell and explains how to use its commands. By default, Cassandra provides a prompt Cassandra query language shell (cqlsh) that allows users to communicate with it. Using this shell, you can execute Cassandra Query Language (CQL). Using cqlsh, you can define a schema, insert data, and execute a query. Starting cqlsh Start cqlsh using the command cqlsh as shown below. It gives the Cassandra cqlsh prompt as output. [hadoop@linux bin]$ cqlsh Connected to Test Cluster at 127.0.0.1:9042. [cqlsh 5.0.1 | Cassandra 2.1.2 | CQL spec 3.2.0 | Native protocol v3] Use HELP for help. cqlsh> Cqlsh − As discussed above, this command is used to start the cqlsh prompt. In addition, it supports a few more options as well. The following table explains all the options of cqlsh and their usage. Options Usage cqlsh –help Shows help topics about the options of cqlsh commands. cqlsh –version Provides the version of the cqlsh you are using. cqlsh –color Directs the shell to use colored output. cqlsh –debug Shows additional debugging information. cqlsh –execute cql_statement Directs the shell to accept and execute a CQL command. cqlsh –file= “file name” If you use this option, Cassandra executes the command in the given file and exits. cqlsh –no-color Directs Cassandra not to use colored output. cqlsh -u “user name” Using this option, you can authenticate a user. The default user name is: cassandra. cqlsh-p “pass word” Using this option, you can authenticate a user with a password. The default password is: cassandra. Cqlsh Commands Cqlsh has a few commands that allow users to interact with it. The commands are listed below. Documented Shell Commands Given below are the Cqlsh documented shell commands. These are the commands used to perform tasks such as displaying help topics, exit from cqlsh, describe,etc. HELP − Displays help topics for all cqlsh commands. CAPTURE − Captures the output of a command and adds it to a file. CONSISTENCY − Shows the current consistency level, or sets a new consistency level. COPY − Copies data to and from Cassandra. DESCRIBE − Describes the current cluster of Cassandra and its objects. EXPAND − Expands the output of a query vertically. EXIT − Using this command, you can terminate cqlsh. PAGING − Enables or disables query paging. SHOW − Displays the details of current cqlsh session such as Cassandra version, host, or data type assumptions. SOURCE − Executes a file that contains CQL statements. TRACING − Enables or disables request tracing. CQL Data Definition Commands CREATE KEYSPACE − Creates a KeySpace in Cassandra. USE − Connects to a created KeySpace. ALTER KEYSPACE − Changes the properties of a KeySpace. DROP KEYSPACE − Removes a KeySpace CREATE TABLE − Creates a table in a KeySpace. ALTER TABLE − Modifies the column properties of a table. DROP TABLE − Removes a table. TRUNCATE − Removes all the data from a table. CREATE INDEX − Defines a new index on a single column of a table. DROP INDEX − Deletes a named index. CQL Data Manipulation Commands INSERT − Adds columns for a row in a table. UPDATE − Updates a column of a row. DELETE − Deletes data from a table. BATCH − Executes multiple DML statements at once. CQL Clauses SELECT − This clause reads data from a table WHERE − The where clause is used along with select to read a specific data. ORDERBY − The orderby clause is used along with select to read a specific data in a specific order. Print Page Previous Next Advertisements ”;