Module: Cequel::Record::SecondaryIndexes

Defined in:
lib/cequel/record/secondary_indexes.rb

Overview

Data columns may be given secondary indexes. This allows you to query the table for records where the indexed column contains a single value. Secondary indexes are not nearly as flexible as primary keys: you cannot query for multiple values or for ranges of values. You also cannot combine a secondary index restriction with a primary key restriction in the same query, nor can you combine more than one secondary index restrictions in the same query.

If a column is given a secondary index, magic finder methods ‘find_by_*`, `find_all_by_*`, and `with_*` are added to the class singleton. See below for an example.

Secondary indexes are fairly expensive for Cassandra and should only be defined where needed.

Examples:

Defining a secondary index

class Post
  belongs_to :blog
  key :id, :timeuuid, auto: true
  column :title, :text
  column :body, :text
  column :author_id, :uuid, index: true # this column has a secondary
                                        # index
end

Using a secondary index

# return the first record with the author_id
Post.find_by_author_id(id)

# return an Array of all records with the author_id
Post.find_all_by_author_id(id)

# return a RecordSet scoped to the author_id
Post.with_author_id(id)

# same as with_author_id
Post.where(:author_id, id)

Since:

  • 1.0.0

Instance Method Summary collapse

Instance Method Details

#column(name, type, options = {}) ⇒ Object

Since:

  • 1.0.0



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/cequel/record/secondary_indexes.rb', line 46

def column(name, type, options = {})
  super
  name = name.to_sym
  if options[:index]
    instance_eval "      def with_\#{name}(value)\n        all.where(\#{name.inspect}, value)\n      end\n\n      def find_by_\#{name}(value)\n        with_\#{name}(value).first\n      end\n\n      def find_all_by_\#{name}(value)\n        with_\#{name}(value).to_a\n      end\n    RUBY\n  end\nend\n", __FILE__, __LINE__+1