Skip to content

Instantly share code, notes, and snippets.

@amussey
Last active December 24, 2015 16:19
Show Gist options
  • Save amussey/6826646 to your computer and use it in GitHub Desktop.
Save amussey/6826646 to your computer and use it in GitHub Desktop.
Cassandra Scripts
cassandra_config.py
*.pyc
project/

Cassandra CQL3 Scripts

Executables

To get a list of the keyspaces and column types in the database, use:

python list_keyspaces.py

Scripting

To print out the return of a select statement, use cql_print_select:

from cassandra_driver import query
from cassandra_cql3_formatting import cql_print_select

call_result = query('SELECT * FROM projects')
cql_print_select(call_result)

This will return:

| key                                  || name         || provider_id      |
-----------------------------------------------------------------------------
| df95812e-2d0f-11e3-97a3-080027880ca6 || New Story    || archive_storage  |
| b1325276-2d14-11e3-9fed-080027880ca6 || Fixing Bugs  || new_wave_systems |
#
# Fill in this information and remove the 'template' from the filename.
#
keyspace = 'keyspace'
hostnames = ['127.0.0.1']
port = 9042
#
# CQL3 Output Formatting
#
import uuid
import sys
def _measure_width(results, column):
full_width = len(column)
for item in results:
# if type(item.__getattribute__(column)) is uuid.UUID:
# return 45
# elif is int:
# current_width = len(str(item.__getattribute__(column)))
# else:
current_width = len(str(item.__getattribute__(column)))
if current_width > full_width:
full_width = current_width
return full_width
def _line_break(column_width, columns):
total_length = 0
for column in columns:
total_length += 4 + column_width[column]
return ''.ljust(total_length, '-')
def cql_print_select(results):
columns = results[0]._fields
column_width = {}
for column in columns:
column_width[column] = _measure_width(results, column)
sys.stdout.write("| {0} |".format(column.ljust(column_width[column], ' ')))
sys.stdout.write('\n{0}\n'.format(_line_break(column_width, columns)))
for item in results:
for column in columns:
sys.stdout.write("| {0} |".format(str(item.__getattribute__(column)).ljust(column_width[column], ' ')))
sys.stdout.write('\n')
LOGGING_ON = False
if LOGGING_ON:
import logging
log = logging.getLogger()
log.setLevel('DEBUG')
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
log.addHandler(handler)
from cassandra.cluster import Cluster
import cassandra_config as config
class Connection(object):
def __init__(self):
super(Connection, self).__init__()
"".encode('utf8')
self.cluster = Cluster(config.hostnames, port=config.port)
self.connect()
def connect(self):
self.session = self.cluster.connect(keyspace=config.keyspace)
connection = Connection()
def query(query_string, parameters=None):
return connection.session.execute(query_string, parameters=parameters)
SHOW_ALL = False
from cassandra_driver import query
rows = query("SELECT * FROM system.schema_columns;")
keyspaces = {}
for row in rows:
if SHOW_ALL or (not row.keyspace_name == 'system' and not row.keyspace_name == 'system_traces'):
if not row.keyspace_name in keyspaces:
keyspaces[row.keyspace_name] = {}
if not row.columnfamily_name in keyspaces[row.keyspace_name]:
keyspaces[row.keyspace_name][row.columnfamily_name] = []
if row.type == 'partition_key':
keyspaces[row.keyspace_name][row.columnfamily_name].insert(0, {
'name': '{0}'.format(row.column_name),
'type': row.validator.replace('org.apache.cassandra.db.marshal.', ''),
'key' : True
})
else:
keyspaces[row.keyspace_name][row.columnfamily_name].append({
'name': row.column_name,
'type': row.validator.replace('org.apache.cassandra.db.marshal.', ''),
'key' : False
})
for keys in keyspaces.keys():
print '{0}:'.format(keys)
for columnfamily in keyspaces[keys].keys():
print ' {0}'.format(columnfamily)
for item in keyspaces[keys][columnfamily]:
key = ' '
if item['key']:
key = '*'
print ' {0} {1}{2}'.format(key, item['name'].ljust(28, ' '), item['type'])
-e git+https://github.com/datastax/python-driver.git#egg=cassandra-driver
#cassandra-driver==1.0.0-beta4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment