Method: Dynamoid::Indexes::ClassMethods#local_secondary_index

Defined in:
lib/dynamoid/indexes.rb

#local_secondary_index(options = {}) ⇒ Object

Defines a local secondary index on a table. Will use the same primary hash key as the table.

Parameters:

  • options (Hash) (defaults to: {})

    options to pass for this index.

Options Hash (options):

  • :name (Symbol)

    the name for the index; this still gets namespaced. If not specified, a name is automatically generated.

  • :range_key (Symbol)

    the range key column for the index.

  • :projected_attributes (Symbol, Array<Symbol>)

    table attributes to project for this index. Can be :keys_only, :all or an array of included fields. If not specified, defaults to :keys_only.



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/dynamoid/indexes.rb', line 66

def local_secondary_index(options={})
  unless options.present?
    raise Dynamoid::Errors::InvalidIndex.new('empty index definition')
  end

  primary_hash_key = self.hash_key
  primary_range_key = self.range_key
  index_range_key = options[:range_key]

  unless index_range_key.present?
    raise Dynamoid::Errors::InvalidIndex.new('A local secondary index '\
      'requires a :range_key to be specified')
  end

  if primary_range_key.present? && index_range_key == primary_range_key
    raise Dynamoid::Errors::InvalidIndex.new('A local secondary index'\
      ' must use a different :range_key than the primary key')
  end

  index_opts = options.merge(
    dynamoid_class: self,
    type: :local_secondary,
    hash_key: primary_hash_key)

  index = Dynamoid::Indexes::Index.new(index_opts)
  key = index_key(primary_hash_key, index_range_key)
  self.local_secondary_indexes[key] = index
  self
end