123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Index::View

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Forwardable
Instance Chain:
Inherits: Object
Defined in: lib/mongo/index/view.rb

Overview

A class representing a view of indexes.

Since:

  • 2.0.0

Constant Summary

  • KEY =

    The index key field.

    Since:

    • 2.0.0

    # File 'lib/mongo/index/view.rb', line 52
    'key'.freeze
  • NAME =

    The index name field.

    Since:

    • 2.0.0

    # File 'lib/mongo/index/view.rb', line 57
    'name'.freeze
  • OPTIONS =

    The mappings of Ruby index options to server options.

    Since:

    • 2.0.0

    # File 'lib/mongo/index/view.rb', line 62
    {
      :background => :background,
      :bits => :bits,
      :bucket_size => :bucketSize,
      :default_language => :default_language,
      :expire_after => :expireAfterSeconds,
      :expire_after_seconds => :expireAfterSeconds,
      :key => :key,
      :language_override => :language_override,
      :max => :max,
      :min => :min,
      :name => :name,
      :partial_filter_expression => :partialFilterExpression,
      :sparse => :sparse,
      :sphere_version => :'2dsphereIndexVersion',
      :storage_engine => :storageEngine,
      :text_version => :textIndexVersion,
      :unique => :unique,
      :version => :v,
      :weights => :weights,
      :collation => :collation,
      :comment => :comment,
      :wildcard_projection => :wildcardProjection,
    }.freeze

Class Method Summary

Instance Attribute Summary

::Mongo::CursorHost - Included

#cursor

Returns the cursor associated with this view, if any.

#timeout_mode

Instance Method Summary

::Mongo::Cursor::NonTailable - Included

#cursor_type

These views are always non-tailable.

#timeout_mode

These views apply timeouts to each iteration of a cursor, as opposed to the entire lifetime of the cursor.

::Mongo::CursorHost - Included

#validate_timeout_mode!

Ensure the timeout mode is appropriate for other options that have been given.

::Mongo::Retryable - Included

#read_worker

Returns the read worker for handling retryable reads.

#select_server

This is a separate method to make it possible for the test suite to assert that server selection is performed during retry attempts.

#write_worker

Returns the write worker for handling retryable writes.

Constructor Details

.new(collection, options = {}) ⇒ View

Create the new index view.

Examples:

Create the new index view.

View::Index.new(collection)

Parameters:

  • collection (Collection)

    The collection.

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

    ::Mongo::Options for getting a list of indexes.

Options Hash (options):

  • :batch_size (Integer)

    The batch size for results returned from the listIndexes command.

  • :timeout_mode (:cursor_lifetime | :iteration)

    How to interpret :timeout_ms (whether it applies to the lifetime of the cursor, or per iteration).

  • :timeout_ms (Integer)

    The operation timeout in milliseconds. Must be a non-negative integer. An explicit value of 0 means infinite. The default value is unset which means the value is inherited from the collection or the database or the client.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 318

def initialize(collection, options = {})
  @collection = collection
  @operation_timeout_ms = options.delete(:timeout_ms)

  validate_timeout_mode!(options)

  @batch_size = options[:batch_size]
  @options = options
end

Instance Attribute Details

#batch_sizeInteger (readonly)

Returns:

  • (Integer)

    batch_size The size of the batch of results when sending the listIndexes command.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 38

attr_reader :batch_size

#collectionCollection (readonly)

Returns:

  • (Collection)

    collection The indexes collection.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 34

attr_reader :collection

#operation_timeout_msInteger | nil | The timeout_ms value that was passed as an option to the view. (readonly)

This method is for internal use only.

Returns:

  • (Integer | nil | The timeout_ms value that was passed as an option to the view.)

    Integer | nil | The timeout_ms value that was passed as an option to the view.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 44

attr_reader :operation_timeout_ms

Instance Method Details

#create_many(*models) ⇒ Result

Note:

On MongoDB 3.0.0 and higher, the indexes will be created in parallel on the server.

Creates multiple indexes on the collection.

Examples:

Create multiple indexes.

view.create_many([
  { key: { name: 1 }, unique: true },
  { key: { age: -1 }, background: true }
])

Create multiple indexes with options.

view.create_many(
  { key: { name: 1 }, unique: true },
  { key: { age: -1 }, background: true },
  { commit_quorum: 'majority' }
)

Parameters:

  • models (Array<Hash>)

    The index specifications. Each model MUST include a :key option, except for the last item in the Array, which may be a Hash specifying options relevant to the createIndexes operation. The following options are accepted:

    • commit_quorum: Specify how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. Potential values are:

      • an integer from 0 to the number of members of the replica set

      • “majority” indicating that a majority of data bearing nodes must vote

      • “votingMembers” which means that all voting data bearing nodes must vote

    • session: The session to use.

    • comment: A user-provided comment to attach to this command.

Returns:

  • (Result)

    The result of the command.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 216

def create_many(*models)
  models = models.flatten
  options = {}
  if models && !models.last.key?(:key)
    options = models.pop
  end

  client.with_session(@options.merge(options)) do |session|
    server = next_primary(nil, session)

    indexes = normalize_models(models, server)
    indexes.each do |index|
      if index[:bucketSize] || index['bucketSize']
        client.log_warn("Haystack indexes (bucketSize index option) are deprecated as of MongoDB 4.4")
      end
    end

    spec = {
      indexes: indexes,
      db_name: database.name,
      coll_name: collection.name,
      session: session,
      commit_quorum: options[:commit_quorum],
      write_concern: write_concern,
      comment: options[:comment],
    }
    context = Operation::Context.new(
      client: client,
      session: session,
      operation_timeouts: operation_timeouts(options)
    )
    Operation::CreateIndex.new(spec).execute(server, context: context)
  end
end

#create_one(keys, options = {}) ⇒ Result

Note:

Note that the options listed may be subset of those available.

Creates an index on the collection.

See the MongoDB documentation for a full list of supported options by server version.

Examples:

Create a unique index on the collection.

view.create_one({ name: 1 }, { unique: true })

Parameters:

  • keys (Hash)

    A hash of field name/direction pairs.

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

    ::Mongo::Options for this index.

Options Hash (options):

  • :unique (true, false) — default: false

    If true, this index will enforce a uniqueness constraint on that field.

  • :background (true, false) — default: false

    If true, the index will be built in the background (only available for server versions >= 1.3.2 )

  • :drop_dups (true, false) — default: false

    If creating a unique index on this collection, this option will keep the first document the database indexes and drop all subsequent documents with duplicate values on this field.

  • :bucket_size (Integer) — default: nil

    For use with geoHaystack indexes. Number of documents to group together within a certain proximity to a given longitude and latitude.

  • :max (Integer) — default: nil

    Specify the max latitude and longitude for a geo index.

  • :min (Integer) — default: nil

    Specify the min latitude and longitude for a geo index.

  • :partial_filter_expression (Hash)

    Specify a filter for a partial index.

  • :hidden (Boolean)

    When :hidden is true, this index will exist on the collection but not be used by the query planner when executing operations.

  • :commit_quorum (String | Integer)

    Specify how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. Potential values are:

    • an integer from 0 to the number of members of the replica set

    • “majority” indicating that a majority of data bearing nodes must vote

    • “votingMembers” which means that all voting data bearing nodes must vote

  • :session (Session)

    The session to use for the operation.

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Result)

    The response.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 167

def create_one(keys, options = {})
  options = options.dup

  create_options = {}
  if session = @options[:session]
    create_options[:session] = session
  end
  %i(commit_quorum session comment timeout_ms max_time_ms).each do |key|
    if value = options.delete(key)
      create_options[key] = value
    end
  end
  create_many({ key: keys }.merge(options), create_options)
end

#drop_all(options = {}) ⇒ Result

Drop all indexes on the collection.

Examples:

Drop all indexes on the collection.

view.drop_all

Parameters:

Options Hash (options):

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Result)

    The response.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 119

def drop_all(options = {})
  drop_by_name(Index::ALL, options)
end

#drop_by_name(name, opts = {}) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 352

def drop_by_name(name, opts = {})
  client.send(:with_session, @options) do |session|
    spec = {
      db_name: database.name,
      coll_name: collection.name,
      index_name: name,
      session: session,
      write_concern: write_concern,
    }
    spec[:comment] = opts[:comment] unless opts[:comment].nil?
    server = next_primary(nil, session)
    context = Operation::Context.new(
      client: client,
      session: session,
      operation_timeouts: operation_timeouts(opts)
    )
    Operation::DropIndex.new(spec).execute(server, context: context)
  end
end

#drop_one(name, options = {}) ⇒ Result

Drop an index by its name.

Examples:

Drop an index by its name.

view.drop_one('name_1')

Parameters:

  • name (String)

    The name of the index.

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

    ::Mongo::Options for this operation.

Options Hash (options):

  • :comment (Object)

    A user-provided comment to attach to this command.

Returns:

  • (Result)

    The response.

Raises:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 101

def drop_one(name, options = {})
  raise Error::MultiIndexDrop.new if name == Index::ALL
  drop_by_name(name, options)
end

#each(&block)

Iterate over all indexes for the collection.

Examples:

Get all the indexes.

view.each do |index|
  ...
end

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 279

def each(&block)
  session = client.get_session(@options)
  context = Operation::Context.new(
    client: client,
    session: session,
    operation_timeouts: operation_timeouts(@options)
  )

  cursor = read_with_retry_cursor(session, ServerSelector.primary, self, context: context) do |server|
    send_initial_query(server, session, context)
  end
  if block_given?
    cursor.each do |doc|
      yield doc
    end
  else
    cursor.to_enum
  end
end

#get(keys_or_name) ⇒ Hash

Convenience method for getting index information by a specific name or spec.

Examples:

Get index information by name.

view.get('name_1')

Get index information by the keys.

view.get(name: 1)

Parameters:

  • keys_or_name (Hash, String)

    The index name or spec.

Returns:

  • (Hash)

    The index information.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 265

def get(keys_or_name)
  find do |index|
    (index[NAME] == keys_or_name) || (index[KEY] == normalize_keys(keys_or_name))
  end
end

#index_name(spec) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 372

def index_name(spec)
  spec.to_a.join('_')
end

#indexes_spec(session) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 376

def indexes_spec(session)
  { selector: {
      listIndexes: collection.name,
      cursor: batch_size ? { batchSize: batch_size } : {} },
    coll_name: collection.name,
    db_name: database.name,
    session: session
  }
end

#initial_query_op(session) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 386

def initial_query_op(session)
  Operation::Indexes.new(indexes_spec(session))
end

#limit (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 390

def limit; -1; end

#normalize_keys(spec) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 392

def normalize_keys(spec)
  return false if spec.is_a?(String)
  Options::Mapper.transform_keys_to_strings(spec)
end

#normalize_models(models, server) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 397

def normalize_models(models, server)
  models.map do |model|
    # Transform options first which gives us a mutable hash
    Options::Mapper.transform(model, OPTIONS).tap do |model|
      model[:name] ||= index_name(model.fetch(:key))
    end
  end
end

#operation_timeouts(opts = {}) ⇒ Hash

This method is for internal use only.

Returns:

  • (Hash)

    timeout_ms value set on the operation level (if any), and/or timeout_ms that is set on collection/database/client level (if any).

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 340

def operation_timeouts(opts = {})
  {}.tap do |result|
    if opts[:timeout_ms] || operation_timeout_ms
      result[:operation_timeout_ms] = opts.delete(:timeout_ms) || operation_timeout_ms
    else
      result[:inherited_timeout_ms] = collection.timeout_ms
    end
  end
end

#send_initial_query(server, session, context) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 406

def send_initial_query(server, session, context)
  if server.load_balancer?
    connection = server.pool.check_out(context: context)
    initial_query_op(session).execute_with_connection(connection, context: context)
  else
    initial_query_op(session).execute(server, context: context)
  end
end

#timeout_msInteger | nil

The timeout_ms value to use for this operation; either specified as an option to the view, or inherited from the collection.

Returns:

  • (Integer | nil)

    the timeout_ms for this operation

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/index/view.rb', line 332

def timeout_ms
  operation_timeout_ms || collection.timeout_ms
end