| by Arround The Web | No comments

Cassandra Create Index

“In Cassandra databases, an index provides a feature for fast and efficient data lookups using data attributes other than the partition key. An index works by creating a separate hidden table containing the values to be indexed.

This article will discuss creating a Cassandra index using the CREATE INDEX command.”

Cassandra Create Index Command Syntax

The snippet below shows the syntax of creating an index.

CREATE INDEX IF NOT EXISTS [index_name]
ON keyspace.table_name ( KEYS ( column_name ) )

 
You can enclose the index_name with single quotes. However, remember that the index name adheres to the Cassandra naming rules, such as excluding reserved keywords.

Example

To illustrate how we can create an index, let us start by creating a sample table, as shown in the code below:

cqlsh:sample> create table sample.user_info( id uuid, full_name text, email text, phone int, country text, primary key(i
d));

 
The command above creates a table called user_info in the sample keyspace. Once we have the target table, we can create an index as shown in the command below:

cqlsh:sample> create index user_loc on sample.user_info (country);

 
The command above will create an index user_loc of the values of the country column. If you do not specify the index name, Cassandra will generate an index name with the format table_name_column_name_idx.

An example is as shown:

cqlsh:sample> create index on sample.user_info (email);

 
In the example above, we can see that we do not specify the name of the index. Once we describe the table:

cqlsh:sample> desc table user_info

 
We can see the index creation command as shown:

CREATE INDEX user_info_email_idx ON sample.user_info (email);

 
As we can see, the index name follows the table_name_column_name_idx format.

We can also create an index on a clustering column as shown:

cqlsh:sample> create table sample.user_info( id uuid, full_name text, email text, phone int, country text, primary key((id, full_name), country));

 
We can then create an index on the clustering column as:

cqlsh:sample> create index on sample.user_info (country);

 

Conclusion

In this post, you learned how to use the Cassandra CREATE INDEX command to create various indexes.

Happy coding!!

Share Button

Source: linuxhint.com

Leave a Reply