Class: Cassandra

Inherits:
Object
  • Object
show all
Includes:
Columns, Helpers, Protocol
Defined in:
lib/cassandra/cassandra.rb,
lib/cassandra.rb,
lib/cassandra/0.8.rb,
lib/cassandra/0.6.rb,
lib/cassandra/0.7.rb,
lib/cassandra/long.rb,
lib/cassandra/helpers.rb,
lib/cassandra/columns.rb,
lib/cassandra/keyspace.rb,
lib/cassandra/protocol.rb,
lib/cassandra/constants.rb,
lib/cassandra/comparable.rb,
lib/cassandra/0.6/columns.rb,
lib/cassandra/0.7/columns.rb,
lib/cassandra/0.8/columns.rb,
lib/cassandra/ordered_hash.rb,
lib/cassandra/0.6/protocol.rb,
lib/cassandra/0.8/protocol.rb,
lib/cassandra/0.7/protocol.rb,
lib/cassandra/0.7/cassandra.rb,
lib/cassandra/0.8/cassandra.rb,
lib/cassandra/column_family.rb,
lib/cassandra/0.6/cassandra.rb,
lib/cassandra/mock.rb

Overview

OrderedHash is namespaced to prevent conflicts with other implementations

Defined Under Namespace

Modules: Columns, Consistency, Constants, Helpers, Protocol Classes: AccessError, ColumnFamily, Comparable, Keyspace, Long, Mock, OrderedHash, OrderedHashInt

Constant Summary

WRITE_DEFAULTS =
{
  :count => 1000,
  :timestamp => nil,
  :consistency => Consistency::ONE,
  :ttl => nil
}
READ_DEFAULTS =
{
  :count => 100,
  :start => nil,
  :finish => nil,
  :reversed => false,
  :consistency => Consistency::ONE
}
THRIFT_DEFAULTS =
{
  :transport_wrapper => Thrift::BufferedTransport,
  :thrift_client_class => ThriftClient
}

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Helpers

#extract_and_validate_params, #s_map

Constructor Details

- (Cassandra) initialize(keyspace, servers = "127.0.0.1:9160", thrift_client_options = {})

Create a new Cassandra instance and open the connection.



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/cassandra/cassandra.rb', line 74

def initialize(keyspace, servers = "127.0.0.1:9160", thrift_client_options = {})
  @is_super = {}
  @column_name_class = {}
  @sub_column_name_class = {}
  @auto_discover_nodes = true
  thrift_client_options[:transport_wrapper] ||= Cassandra.DEFAULT_TRANSPORT_WRAPPER
  @thrift_client_options = THRIFT_DEFAULTS.merge(thrift_client_options)
  @thrift_client_class = @thrift_client_options[:thrift_client_class]
  @keyspace = keyspace
  @servers = Array(servers)
end

Instance Attribute Details

- (Object) auth_request (readonly)

Returns the value of attribute auth_request



67
68
69
# File 'lib/cassandra/cassandra.rb', line 67

def auth_request
  @auth_request
end

- (Object) keyspace

Returns the value of attribute keyspace



67
68
69
# File 'lib/cassandra/cassandra.rb', line 67

def keyspace
  @keyspace
end

- (Object) servers (readonly)

Returns the value of attribute servers



67
68
69
# File 'lib/cassandra/cassandra.rb', line 67

def servers
  @servers
end

- (Object) thrift_client_class (readonly)

Returns the value of attribute thrift_client_class



67
68
69
# File 'lib/cassandra/cassandra.rb', line 67

def thrift_client_class
  @thrift_client_class
end

- (Object) thrift_client_options (readonly)

Returns the value of attribute thrift_client_options



67
68
69
# File 'lib/cassandra/cassandra.rb', line 67

def thrift_client_options
  @thrift_client_options
end

Class Method Details

+ (Object) DEFAULT_TRANSPORT_WRAPPER



69
70
71
# File 'lib/cassandra/cassandra.rb', line 69

def self.DEFAULT_TRANSPORT_WRAPPER
  Thrift::BufferedTransport
end

+ (Object) VERSION



2
3
4
# File 'lib/cassandra/0.8.rb', line 2

def self.VERSION
  "0.7"
end

Instance Method Details

- (Object) add(column_family, key, value, *columns_and_options)

Add a value to the counter in cf:key:super column:column



6
7
8
9
# File 'lib/cassandra/0.8/cassandra.rb', line 6

def add(column_family, key, value, *columns_and_options)
  column_family, column, sub_column, options = extract_and_validate_params(column_family, key, columns_and_options, WRITE_DEFAULTS)
  _add(column_family, key, column, sub_column, value, options[:consistency])
end

- (Object) add_column_family(cf_def)

Creates a new column family from the passed in Cassandra::ColumnFamily instance, and returns the schema id.



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/cassandra/cassandra.rb', line 257

def add_column_family(cf_def)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_add_column_family(cf_def)
  rescue CassandraThrift::TimedOutException => te
    puts "Timed out: #{te.inspect}"
  end
  @schema = nil
  res
end

- (Object) add_keyspace(ks_def)

Add keyspace using the passed in keyspace definition.

Returns the new schema id.



324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/cassandra/cassandra.rb', line 324

def add_keyspace(ks_def)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_add_keyspace(ks_def)
  rescue CassandraThrift::TimedOutException => toe
    puts "Timed out: #{toe.inspect}"
  rescue Thrift::TransportException => te
    puts "Timed out: #{te.inspect}"
  end
  @keyspaces = nil
  res
end

- (Object) batch(options = {})

Open a batch operation and yield self. Inserts and deletes will be queued until the block closes, and then sent atomically to the server. Supports the :consistency option, which overrides the consistency set in the individual commands.



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# File 'lib/cassandra/cassandra.rb', line 819

def batch(options = {})
  _, _, _, options = 
    extract_and_validate_params(schema.keys.first, "", [options], WRITE_DEFAULTS)

  @batch = []
  yield(self)
  compacted_map,seen_clevels = compact_mutations!
  clevel = if options[:consistency] != nil # Override any clevel from individual mutations if 
             options[:consistency]
           elsif seen_clevels.length > 1 # Cannot choose which CLevel to use if there are several ones
             raise "Multiple consistency levels used in the batch, and no override...cannot pick one" 
           else # if no consistency override has been provided but all the clevels in the batch are the same: use that one
             seen_clevels.first
           end

  _mutate(compacted_map,clevel)
ensure
  @batch = nil
end

- (Object) clear_keyspace!(options = {})

Remove all rows in the keyspace. Supports options :consistency and :timestamp. FIXME May not currently delete all records without multiple calls. Waiting for ranged remove support in Cassandra.



247
248
249
# File 'lib/cassandra/cassandra.rb', line 247

def clear_keyspace!(options = {})
  schema.keys.each { |column_family| clear_column_family!(column_family, options) }
end

- (Object) cluster_name

Returns the string name specified for the cluster.

Please note that this only works on version 0.7.0 and higher.



196
197
198
199
200
# File 'lib/cassandra/cassandra.rb', line 196

def cluster_name
  return false if Cassandra.VERSION.to_f < 0.7

  @cluster_name ||= client.describe_cluster_name()
end

- (Object) count_columns(column_family, key, *columns_and_options)

Count the columns for the provided parameters.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :consistency - Uses the default read consistency if none specified.



502
503
504
505
506
# File 'lib/cassandra/cassandra.rb', line 502

def count_columns(column_family, key, *columns_and_options)
  column_family, super_column, _, options = 
    extract_and_validate_params(column_family, key, columns_and_options, READ_DEFAULTS)      
  _count_columns(column_family, key, super_column, options[:consistency])
end

- (Object) count_range(column_family, options = {})

Count all rows in the column_family you request.

This method just calls Cassandra#get_range_keys and returns the number of records returned.

See Cassandra#get_range for options.



768
769
770
# File 'lib/cassandra/cassandra.rb', line 768

def count_range(column_family, options = {})
  get_range_keys(column_family, options).length
end

- (Object) create_index(keyspace, column_family, column_name, validation_class)

Create secondary index.

  • keyspace

  • column_family

  • column_name

  • validation_class



847
848
849
850
851
852
853
854
855
856
857
858
859
860
# File 'lib/cassandra/cassandra.rb', line 847

def create_index(keyspace, column_family, column_name, validation_class)
  return false if Cassandra.VERSION.to_f < 0.7

  cf_def = client.describe_keyspace(keyspace).cf_defs.find{|x| x.name == column_family}
  if !cf_def.nil? and !cf_def..find{|x| x.name == column_name}
    c_def  = CassandraThrift::ColumnDef.new do |cd|
      cd.name             = column_name
      cd.validation_class = "org.apache.cassandra.db.marshal."+validation_class
      cd.index_type       = CassandraThrift::IndexType::KEYS
    end
    cf_def..push(c_def)
    update_column_family(cf_def)
  end
end

- (Object) create_index_clause(index_expressions, start = "", count = 100) Also known as: create_idx_clause

This method takes an array if CassandraThrift::IndexExpression objects and creates a CassandraThrift::IndexClause for use in the Cassandra#get_index_slices

  • index_expressions - Array of CassandraThrift::IndexExpressions.

  • start - The starting row key.

  • count - The count of items to be returned



917
918
919
920
921
922
923
924
# File 'lib/cassandra/cassandra.rb', line 917

def create_index_clause(index_expressions, start = "", count = 100)
  return false if Cassandra.VERSION.to_f < 0.7

  CassandraThrift::IndexClause.new(
    :start_key    => start,
    :expressions  => index_expressions,
    :count        => count)
end

- (Object) create_index_expression(column_name, value, comparison) Also known as: create_idx_expr

This method is mostly used internally by get_index_slices to create a CassandraThrift::IndexExpression for the given options.

  • column_name - Column to be compared

  • value - Value to compare against

  • comparison - Type of comparison to do.



887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
# File 'lib/cassandra/cassandra.rb', line 887

def create_index_expression(column_name, value, comparison)
  return false if Cassandra.VERSION.to_f < 0.7

  CassandraThrift::IndexExpression.new(
    :column_name => column_name,
    :value => value,
    :op => (case comparison
              when nil, "EQ", "eq", "=="
                CassandraThrift::IndexOperator::EQ
              when "GTE", "gte", ">="
                CassandraThrift::IndexOperator::GTE
              when "GT", "gt", ">"
                CassandraThrift::IndexOperator::GT
              when "LTE", "lte", "<="
                CassandraThrift::IndexOperator::LTE
              when "LT", "lt", "<"
                CassandraThrift::IndexOperator::LT
            end ))
end

- (Object) default_read_consistency=(value)

The initial default consistency is set to ONE, but you can use this method to override the normal default with your specified value. Use this if you do not want to specify a read consistency for each query.



410
411
412
# File 'lib/cassandra/cassandra.rb', line 410

def default_read_consistency=(value)
  READ_DEFAULTS[:consistency] = value
end

- (Object) default_write_consistency=(value)

The initial default consistency is set to ONE, but you can use this method to override the normal default with your specified value. Use this if you do not want to specify a write consistency for each insert statement.



401
402
403
# File 'lib/cassandra/cassandra.rb', line 401

def default_write_consistency=(value)
  WRITE_DEFAULTS[:consistency] = value
end

- (Object) disable_node_auto_discovery!

This is primarily helpful when the cassandra cluster is communicating internally on a different ip address than what you are using to connect. A prime example of this would be when using EC2 to host a cluster. Typically, the cluster would be communicating over the local ip addresses issued by Amazon, but any clients connecting from outside EC2 would need to use the public ip.



98
99
100
# File 'lib/cassandra/cassandra.rb', line 98

def disable_node_auto_discovery!
  @auto_discover_nodes = false
end

- (Object) disconnect!

Disconnect the current client connection.



105
106
107
108
109
110
# File 'lib/cassandra/cassandra.rb', line 105

def disconnect!
  if @client
    @client.disconnect!
    @client = nil
  end
end

- (Object) drop_column_family(column_family)

Delete the specified column family. Return the new schema id.

  • column_family - The column_family name to drop.



274
275
276
277
278
279
280
281
282
283
284
# File 'lib/cassandra/cassandra.rb', line 274

def drop_column_family(column_family)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_drop_column_family(column_family)
  rescue CassandraThrift::TimedOutException => te
    puts "Timed out: #{te.inspect}"
  end
  @schema = nil
  res
end

- (Object) drop_index(keyspace, column_family, column_name)

Delete secondary index.

  • keyspace

  • column_family

  • column_name



869
870
871
872
873
874
875
876
877
# File 'lib/cassandra/cassandra.rb', line 869

def drop_index(keyspace, column_family, column_name)
  return false if Cassandra.VERSION.to_f < 0.7

  cf_def = client.describe_keyspace(keyspace).cf_defs.find{|x| x.name == column_family}
  if !cf_def.nil? and cf_def..find{|x| x.name == column_name}
    cf_def..delete_if{|x| x.name == column_name}
    update_column_family(cf_def)
  end
end

- (Object) drop_keyspace(keyspace)

Deletes keyspace using the passed in keyspace name.

Returns the new schema id.



343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/cassandra/cassandra.rb', line 343

def drop_keyspace(keyspace)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_drop_keyspace(keyspace)
  rescue CassandraThrift::TimedOutException => toe
    puts "Timed out: #{toe.inspect}"
  rescue Thrift::TransportException => te
    puts "Timed out: #{te.inspect}"
  end
  keyspace = "system" if keyspace.eql?(@keyspace)
  @keyspaces = nil
  res
end

- (Object) each(column_family, options = {})

Iterate through each row in the given column family

This method just calls Cassandra#get_range and yields the key and columns.

See Cassandra#get_range for options.



806
807
808
809
810
# File 'lib/cassandra/cassandra.rb', line 806

def each(column_family, options = {})
  get_range_batch(column_family, options) do |key, columns|
    yield key, columns
  end
end

- (Object) each_key(column_family, options = {})

Iterate through each key within the given parameters. This function can be used to iterate over each key in the given column family.

This method just calls Cassandra#get_range and yields each row key.

See Cassandra#get_range for options.



792
793
794
795
796
# File 'lib/cassandra/cassandra.rb', line 792

def each_key(column_family, options = {})
  get_range_batch(column_family, options) do |key, columns|
    yield key
  end
end

- (Boolean) exists?(column_family, key, *columns_and_options)

Return true if the column_family:key::[sub_column] path you request exists.

If passed in only a row key it will query for any columns (limiting to 1) for that row key. If a column is passed in it will query for that specific column/super column.

This method will return true or false.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :consistency - Uses the default read consistency if none specified.

Returns:

  • (Boolean)


630
631
632
633
634
635
636
637
638
639
640
# File 'lib/cassandra/cassandra.rb', line 630

def exists?(column_family, key, *columns_and_options)
  column_family, column, sub_column, options = 
    extract_and_validate_params(column_family, key, columns_and_options, READ_DEFAULTS)
  result = if column
             _multiget(column_family, [key], column, sub_column, 1, '', '', false, options[:consistency])[key]
           else
             _multiget(column_family, [key], nil, nil, 1, '', '', false, options[:consistency])[key]
           end

  ![{}, nil].include?(result)
end

- (Object) get(column_family, key, *columns_and_options)

Return a hash (actually, a Cassandra::OrderedHash) or a single value representing the element at the column_family:key::[sub_column] path you request.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :count - The number of columns requested to be returned.

    • :start - The starting value for selecting a range of columns.

    • :finish - The final value for selecting a range of columns.

    • :reversed - If set to true the results will be returned in

      reverse order.
    • :consistency - Uses the default read consistency if none specified.



577
578
579
# File 'lib/cassandra/cassandra.rb', line 577

def get(column_family, key, *columns_and_options)
  multi_get(column_family, [key], *columns_and_options)[key]
end

- (Object) get_columns(column_family, key, *columns_and_options)

Return a hash of column value pairs for the path you request.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :consistency - Uses the default read consistency if none specified.



536
537
538
539
540
# File 'lib/cassandra/cassandra.rb', line 536

def get_columns(column_family, key, *columns_and_options)
  column_family, columns, sub_columns, options = 
    extract_and_validate_params(column_family, key, columns_and_options, READ_DEFAULTS)      
  _get_columns(column_family, key, columns, sub_columns, options[:consistency])
end

- (Object) get_indexed_slices(column_family, index_clause, *columns_and_options)

This method is used to query a secondary index with a set of provided search parameters

Please note that you can either specify a CassandraThrift::IndexClause or an array of hashes with the format as below.

  • column_family - The Column Family this operation will be run on.

  • index_clause - This can either be a CassandraThrift::IndexClause or an array of hashes with the following keys:

    • :column_name - Column to be compared

    • :value - Value to compare against

    • :comparison - Type of comparison to do.

  • options

    • :key_count - Set maximum number of rows to return. (Only works if CassandraThrift::IndexClause is not passed in.)

    • :key_start - Set starting row key for search. (Only works if CassandraThrift::IndexClause is not passed in.)

    • :consistency

TODO: Supercolumn support.



946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
# File 'lib/cassandra/cassandra.rb', line 946

def get_indexed_slices(column_family, index_clause, *columns_and_options)
  return false if Cassandra.VERSION.to_f < 0.7

  column_family, columns, _, options =
    extract_and_validate_params(column_family, [], columns_and_options, READ_DEFAULTS.merge(:key_count => 100, :key_start => ""))

  if index_clause.class != CassandraThrift::IndexClause
    index_expressions = index_clause.collect do |expression|
      create_index_expression(expression[:column_name], expression[:value], expression[:comparison])
    end

    index_clause = create_index_clause(index_expressions, options[:key_start], options[:key_count])
  end

  key_slices = _get_indexed_slices(column_family, index_clause, columns, options[:count], options[:start],
    options[:finish], options[:reversed], options[:consistency])

  key_slices.inject({}){|h, key_slice| h[key_slice.key] = key_slice.columns; h}
end

- (Object) get_range(column_family, options = {})

Return an Cassandra::OrderedHash containing the columns specified for the given range of keys in the column_family you request.

This method is just a convenience wrapper around Cassandra#get_range_single and Cassandra#get_range_batch. If :key_size, :batch_size, or a block is passed in Cassandra#get_range_batch will be called. Otherwise Cassandra#get_range_single will be used.

The start_key and finish_key parameters are only useful for iterating of all records as is done in the Cassandra#each and Cassandra#each_key methods if you are using the RandomPartitioner.

If the table is partitioned with OrderPreservingPartitioner you may use the start_key and finish_key params to select all records with the same prefix value.

If a block is passed in we will yield the row key and columns for each record returned.

Please note that Cassandra returns a row for each row that has existed in the system since gc_grace_seconds. This is because deleted row keys are marked as deleted, but left in the system until the cluster has had resonable time to replicate the deletion. This function attempts to suppress deleted rows (actually any row returned without columns is suppressed).

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :start_key - The starting value for selecting a range of keys (only useful with OPP).

    • :finish_key - The final value for selecting a range of keys (only useful with OPP).

    • :key_count - The total number of keys to return from the query. (see note regarding deleted records)

    • :batch_size - The maximum number of keys to return per query. If specified will loop until :key_count is obtained or all records have been returned.

    • :count - The number of columns requested to be returned.

    • :start - The starting value for selecting a range of columns.

    • :finish - The final value for selecting a range of columns.

    • :reversed - If set to true the results will be returned in reverse order.

    • :consistency - Uses the default read consistency if none specified.



683
684
685
686
687
688
689
# File 'lib/cassandra/cassandra.rb', line 683

def get_range(column_family, options = {})
  if block_given? || options[:key_count] || options[:batch_size]
    get_range_batch(column_family, options)
  else
    get_range_single(column_family, options)
  end
end

- (Object) get_range_batch(column_family, options = {})

Return an Cassandra::OrderedHash containing the columns specified for the given range of keys in the column_family you request.

If a block is passed in we will yield the row key and columns for each record returned.

See Cassandra#get_range for more details.



731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/cassandra/cassandra.rb', line 731

def get_range_batch(column_family, options = {})
  batch_size    = options.delete(:batch_size) || 100
  count         = options.delete(:key_count)
  result        = {}

  options[:start_key] ||= ''
  last_key  = nil

  while options[:start_key] != last_key && (count.nil? || count > result.length)
    options[:start_key] = last_key
    res = get_range_single(column_family, options.merge!(:start_key => last_key,
                                                         :key_count => batch_size,
                                                         :return_empty_rows => true
                                                        ))
    res.each do |key, columns|
      next if options[:start_key] == key
      next if result.length == count

      unless columns == {}
        yield key, columns if block_given?
        result[key] = columns
      end
      last_key = key
    end
  end

  result
end

- (Object) get_range_keys(column_family, options = {})

Return an Array containing all of the keys within a given range.

This method just calls Cassandra#get_range and returns the row keys for the records returned.

See Cassandra#get_range for options.



780
781
782
# File 'lib/cassandra/cassandra.rb', line 780

def get_range_keys(column_family, options = {})
  get_range(column_family,options.merge!(:count => 1)).keys
end

- (Object) get_range_single(column_family, options = {})

Return an Cassandra::OrderedHash containing the columns specified for the given range of keys in the column_family you request.

See Cassandra#get_range for more details.



697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
# File 'lib/cassandra/cassandra.rb', line 697

def get_range_single(column_family, options = {})
  return_empty_rows = options.delete(:return_empty_rows) || false

  column_family, _, _, options = 
    extract_and_validate_params(column_family, "", [options], 
                                READ_DEFAULTS.merge(:start_key  => '',
                                                    :end_key    => '',
                                                    :key_count  => 100,
                                                    :columns    => nil
                                                   )
                               )

  results = _get_range( column_family,
                        options[:start_key].to_s,
                        options[:finish_key].to_s,
                        options[:key_count],
                        options[:columns],
                        options[:start].to_s,
                        options[:finish].to_s,
                        options[:count],
                        options[:consistency] )

  multi_key_slices_to_hash(column_family, results, return_empty_rows)
end

- (Object) insert(column_family, key, hash, options = {})

This is the main method used to insert rows into cassandra. If the column_family that you are inserting into is a SuperColumnFamily then the hash passed in should be a nested hash, otherwise it should be a flat hash.

This method can also be called while in batch mode. If in batch mode then we queue up the mutations (an insert in this case) and pass them to cassandra in a single batch at the end of the block.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • hash - The columns or super columns to insert.

  • options - Valid options are:

    • :timestamp - Uses the current time if none specified.

    • :consistency - Uses the default write consistency if none specified.

    • :ttl - If specified this is the number of seconds after the insert that this value will be available.



432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/cassandra/cassandra.rb', line 432

def insert(column_family, key, hash, options = {})
  column_family, _, _, options = extract_and_validate_params(column_family, key, [options], WRITE_DEFAULTS)

  timestamp = options[:timestamp] || Time.stamp
  mutation_map = if is_super(column_family)
    {
      key => {
        column_family => hash.collect{|k,v| _super_insert_mutation(column_family, k, v, timestamp, options[:ttl]) }
      }
    }
  else
    {
      key => {
        column_family => hash.collect{|k,v| _standard_insert_mutation(column_family, k, v, timestamp, options[:ttl])}
      }
    }
  end

  @batch ? @batch << [mutation_map, options[:consistency]] : _mutate(mutation_map, options[:consistency])
end

- (Object) inspect



130
131
132
133
134
# File 'lib/cassandra/cassandra.rb', line 130

def inspect
  "#<Cassandra:#{object_id}, @keyspace=#{keyspace.inspect}, @schema={#{
    schema(false).map {|name, hash| ":#{name} => #{hash['type'].inspect}"}.join(', ')
  }}, @servers=#{servers.inspect}>"
end

- (Object) keyspaces

Returns an array of available keyspaces.



151
152
153
# File 'lib/cassandra/cassandra.rb', line 151

def keyspaces
  @keyspaces ||= client.describe_keyspaces()
end

- (Object) login!(username, password)

Issues a login attempt using the username and password specified.

  • username

  • password



118
119
120
121
122
# File 'lib/cassandra/cassandra.rb', line 118

def login!(username, password)
  @auth_request = CassandraThrift::AuthenticationRequest.new
  @auth_request.credentials = {'username' => username, 'password' => password}
  client.(@keyspace, @auth_request)
end

- (Object) multi_count_columns(column_family, keys, *options)

Multi-key version of Cassandra#count_columns. Please note that this queries the server for each key passed in.

Supports same parameters as Cassandra#count_columns.

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :consistency - Uses the default read consistency if none specified.

FIXME: Not real multi; needs server support



522
523
524
# File 'lib/cassandra/cassandra.rb', line 522

def multi_count_columns(column_family, keys, *options)
  OrderedHash[*keys.map { |key| [key, count_columns(column_family, key, *options)] }._flatten_once]
end

- (Object) multi_get(column_family, keys, *columns_and_options)

Multi-key version of Cassandra#get.

This method allows you to select multiple rows with a single query. If a key that is passed in doesn't exist an empty hash will be returned.

Supports the same parameters as Cassandra#get.

  • column_family - The column_family that you are inserting into.

  • key - An array of keys to.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :count - The number of columns requested to be returned.

    • :start - The starting value for selecting a range of columns.

    • :finish - The final value for selecting a range of columns.

    • :reversed - If set to true the results will be returned in reverse order.

    • :consistency - Uses the default read consistency if none specified.



601
602
603
604
605
606
607
608
609
610
611
# File 'lib/cassandra/cassandra.rb', line 601

def multi_get(column_family, keys, *columns_and_options)
  column_family, column, sub_column, options = 
    extract_and_validate_params(column_family, keys, columns_and_options, READ_DEFAULTS)

  hash = _multiget(column_family, keys, column, sub_column, options[:count], options[:start], options[:finish], options[:reversed], options[:consistency])

  # Restore order
  ordered_hash = OrderedHash.new
  keys.each { |key| ordered_hash[key] = hash[key] || (OrderedHash.new if is_super(column_family) and !sub_column) }
  ordered_hash
end

- (Object) multi_get_columns(column_family, keys, *options)

Multi-key version of Cassandra#get_columns. Please note that this queries the server for each key passed in.

Supports same parameters as Cassandra#get_columns

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :consistency - Uses the default read consistency if none specified.

FIXME Not real multi; needs to use a Column predicate



556
557
558
# File 'lib/cassandra/cassandra.rb', line 556

def multi_get_columns(column_family, keys, *options)
  OrderedHash[*keys.map { |key| [key, get_columns(column_family, key, *options)] }._flatten_once]
end

- (Object) partitioner

Returns a string identifying which partitioner is in use by the current cluster. Typically, this will be RandomPartitioner, but it could be OrderPreservingPartioner as well.

Please note that this only works on version 0.7.0 and higher.



220
221
222
223
224
# File 'lib/cassandra/cassandra.rb', line 220

def partitioner
  return false if Cassandra.VERSION.to_f < 0.7

  client.describe_partitioner()
end

- (Object) remove(column_family, key, *columns_and_options)

This method is used to delete (actually marking them as deleted with a tombstone) columns or super columns.

This method can also be used in batch mode. If in batch mode then we queue up the mutations (a deletion in this case)

  • column_family - The column_family that you are inserting into.

  • key - The row key to insert.

  • columns - Either a single super_column or a list of columns.

  • sub_columns - The list of sub_columns to select.

  • options - Valid options are:

    • :timestamp - Uses the current time if none specified.

    • :consistency - Uses the default write consistency if none specified.

TODO: we could change this function or add another that support multi-column removal (by list or predicate)



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'lib/cassandra/cassandra.rb', line 471

def remove(column_family, key, *columns_and_options)
  column_family, column, sub_column, options = extract_and_validate_params(column_family, key, columns_and_options, WRITE_DEFAULTS)

  if @batch
    mutation_map = 
      {
        key => {
          column_family => [ _delete_mutation(column_family, column, sub_column, options[:timestamp]|| Time.stamp) ]
        }
      }
    @batch << [mutation_map, options[:consistency]]
  else 
    # Let's continue using the 'remove' thrift method...not sure about the implications/performance of using the mutate instead
    # Otherwise we coul get use the mutation_map above, and do _mutate(mutation_map, options[:consistency])
    args = {:column_family => column_family}
    columns = is_super(column_family) ? {:super_column => column, :column => sub_column} : {:column => column}
    column_path = CassandraThrift::ColumnPath.new(args.merge(columns))
    _remove(key, column_path, options[:timestamp] || Time.stamp, options[:consistency])
  end
end

- (Object) rename_column_family(old_name, new_name)

Rename a column family. Returns the new schema id.

  • old_name - The current column_family name.

  • new_name - The desired column_family name.



292
293
294
295
296
297
298
299
300
301
302
# File 'lib/cassandra/cassandra.rb', line 292

def rename_column_family(old_name, new_name)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_rename_column_family(old_name, new_name)
  rescue CassandraThrift::TimedOutException => te
    puts "Timed out: #{te.inspect}"
  end
  @schema = nil
  res
end

- (Object) rename_keyspace(old_name, new_name)

Renames keyspace.

  • old_name - Current keyspace name.

  • new_name - Desired keyspace name.

Returns the new schema id



365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/cassandra/cassandra.rb', line 365

def rename_keyspace(old_name, new_name)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_rename_keyspace(old_name, new_name)
  rescue CassandraThrift::TimedOutException => toe
    puts "Timed out: #{toe.inspect}"
  rescue Thrift::TransportException => te
    puts "Timed out: #{te.inspect}"
  end
  keyspace = new_name if old_name.eql?(@keyspace)
  @keyspaces = nil
  res
end

- (Object) ring

Returns an array of CassandraThrift::TokenRange objects indicating which servers make up the current ring. What their start and end tokens are, and their list of endpoints.

Please note that this only works on version 0.7.0 and higher.



208
209
210
211
212
# File 'lib/cassandra/cassandra.rb', line 208

def ring
  return false if Cassandra.VERSION.to_f < 0.7

  client.describe_ring(@keyspace)
end

- (Boolean) schema_agreement?

This returns true if all servers are in agreement on the schema.

Please note that this only works on version 0.7.0 and higher.

Returns:

  • (Boolean)


176
177
178
179
180
# File 'lib/cassandra/cassandra.rb', line 176

def schema_agreement?
  return false if Cassandra.VERSION.to_f < 0.7

  client.describe_schema_versions().length == 1
end

- (Object) update_column_family(cf_def)

Update the column family based on the passed in definition.



307
308
309
310
311
312
313
314
315
316
317
# File 'lib/cassandra/cassandra.rb', line 307

def update_column_family(cf_def)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_update_column_family(cf_def)
  rescue CassandraThrift::TimedOutException => te
    puts "Timed out: #{te.inspect}"
  end
  @schema = nil
  res
end

- (Object) update_keyspace(ks_def)

Update the keyspace using the passed in keyspace definition.



383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/cassandra/cassandra.rb', line 383

def update_keyspace(ks_def)
  return false if Cassandra.VERSION.to_f < 0.7

  begin
    res = client.system_update_keyspace(ks_def)
  rescue CassandraThrift::TimedOutException => toe
    puts "Timed out: #{toe.inspect}"
  rescue Thrift::TransportException => te
    puts "Timed out: #{te.inspect}"
  end
  @keyspaces = nil
  res
end

- (Object) version

Lists the current cassandra.thrift version.

Please note that this only works on version 0.7.0 and higher.



186
187
188
189
190
# File 'lib/cassandra/cassandra.rb', line 186

def version
  return false if Cassandra.VERSION.to_f < 0.7

  client.describe_version()
end