MongoCollection::ensureIndex
(PECL mongo >=0.9.0)
MongoCollection::ensureIndex — Creates an index on the specified field(s) if it does not already exist.
Description
$key|keys
[, array $options
= array()
] )This method is deprecated since version 1.5.0. Please use MongoCollection::createIndex() instead.
Creates an index on the specified field(s) if it does not already exist. Fields may be indexed with a direction (e.g. ascending or descending) or a special type (e.g. text, geospatial, hashed).
Note:
This method will use the » createIndexes database command when communicating with MongoDB 2.6+. For previous database versions, the method will perform an insert operation on the special system.indexes collection.
Parameters
-
keys
-
An array specifying the index's fields as its keys. For each field, the value is either the index direction or » index type. If specifying direction, specify 1 for ascending or -1 for descending.
-
options
-
An array of options for the index creation. Currently available options include:
"unique"
Specify
TRUE
to create a unique index. The default value isFALSE
. This option applies only to ascending/descending indexes.Note:
When MongoDB indexes a field, if a document does not have a value for the field, a
NULL
value is indexed. If multiple documents do not contain a field, a unique index will reject all but the first of those documents. The "sparse" option may be used to overcome this, since it will prevent documents without the field from being indexed."dropDups"
Specify
TRUE
to force creation of a unique index that may have duplicates. MongoDB will index the first occurrence of a key and delete all documents from the collection that contain subsequent occurrences of that key. The default value isFALSE
.Warning"dropDups" may delete data from your database. Use with extreme caution.
"sparse"
Specify
TRUE
to create a sparse index, which only indexes documents containing a specified field. The default value isFALSE
."expireAfterSeconds"
The value of this option should specify the number of seconds after which a document should be considered expired and automatically removed from the collection. This option is only compatible with single-field indexes where the field will contain MongoDate values.
Note:
This feature is available in MongoDB 2.2+. See » Expire Data from Collections by Setting TTL for more information.
"name"
A optional name that uniquely identifies the index.
Note:
By default, the driver will generate an index name based on the index's field(s) and ordering or type. For example, a compound index array("x" => 1, "y" => -1) would be named "x_1_y_-1" and a geospatial index array("loc" => "2dsphere") would be named "loc_2dsphere". For indexes with many fields, it is possible that the generated name might exceed MongoDB's » limit for index names. The "name" option may be used in that case to supply a shorter name.
"socketTimeoutMS"
Integer, defaults to MongoCursor::$timeout. If acknowledged writes are used, this sets how long (in milliseconds) for the client to wait for a database response. If the database does not respond within the timeout period, a MongoCursorTimeoutException will be thrown.
The following option may be used with MongoDB 2.6+:
"maxTimeMS"
Specifies a cumulative time limit in milliseconds for processing the operation (does not include idle time). If the operation is not completed within the timeout period, a MongoExecutionTimeoutException will be thrown.
The following options may be used with MongoDB versions before 2.6:
"w"
See Write Concerns. The default value for MongoClient is 1.
"wTimeoutMS"
How long to wait for write concern acknowledgement. The default value for MongoClient is 10000 milliseconds.
The following options are deprecated and should no longer be used:
"safe"
Deprecated. Please use the write concern "w" option.
"timeout"
Deprecated alias for "socketTimeoutMS".
"wtimeout"
Deprecated alias for "wTimeoutMS".
Return Values
Returns an array containing the status of the index creation. The array contains whether the operation succeeded ("ok"), the number of indexes before and after the operation ("numIndexesBefore" and "numIndexesAfter"), and whether the collection that the index belongs to has been created ("createdCollectionAutomatically"). If the index already existed and did not need to be created, a "note" field may be present in lieu of "numIndexesAfter".
With MongoDB 2.4 and earlier, a status document is only returned if the
write concern is at least
1. Otherwise, TRUE
is returned. The fields in the status
document are different, except for the "ok" field, which
signals whether the index creation was successful. Additional fields are
described in the documentation for
MongoCollection::insert().
Changelog
Version | Description |
---|---|
1.5.0 |
Renamed the "wtimeout" option to
"wTimeoutMS". Emits
Renamed the "timeout" option to
"socketTimeoutMS". Emits
Emits |
1.3.4 | Added "wtimeout" option. |
1.3.0 |
Added "w" option.
The |
1.2.11 |
Emits E_DEPRECATED when
options is scalar.
|
1.2.0 | Added "timeout" option. |
1.0.11 |
The "safe" option will trigger a primary failover, if necessary. MongoException will be thrown if the index name (either generated or set) is longer than 128 bytes. |
1.0.5 | Added the "name" option to override index name creation. |
1.0.2 |
Changed options parameter from boolean to array.
Pre-1.0.2, the second parameter was an optional boolean value specifying
a unique index.
|
Errors/Exceptions
Throws MongoException if the index name is longer than 128 bytes, or if the index specification is not an array.
Throws MongoDuplicateKeyException if the server could not create the unique index due to conflicting documents.
Throws MongoResultException if the server could not create the index due to an error.
Throws MongoCursorException if the "w" option is set and the write fails.
Throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
Examples
Example #1 MongoCollection::ensureIndex() example
<?php
$c = new MongoCollection($db, 'foo');
// create an index on 'x' ascending
$c->ensureIndex(array('x' => 1));
// create a unique index on 'y'
$c->ensureIndex(array('y' => 1), array('unique' => true));
// create a compound index on 'za' ascending and 'zb' descending
$c->ensureIndex(array('za' => 1, 'zb' => -1));
?>
Example #2 Geospatial Indexing
Mongo supports geospatial indexes, which allow you to search for documents near a given location or within a shape. The following example creates a geospatial index on the "loc" field:
<?php
$collection->ensureIndex(array('loc' => '2dsphere'));
?>
Example #3 Drop duplicates example
<?php
$collection->insert(array('username' => 'joeschmoe'));
$collection->insert(array('username' => 'joeschmoe'));
/* Index creation fails, since you cannot create a unique index on a field when
* duplicates exist.
*/
$collection->ensureIndex(array('username' => 1), array('unique' => 1));
/* MongoDB will one of the conflicting documents and allow the unique index to
* be created.
*/
$collection->ensureIndex(array('username' => 1), array('unique' => 1, 'dropDups' => 1));
/* We now have a unique index and subsequent inserts with the same username will
* fail.
*/
$collection->insert(array('username' => 'joeschmoe'));
?>
See Also
- MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- The MongoDB » index and » index type documentation.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- MongoDB
- Базовые классы
- Функция MongoCollection::aggregate() - Perform an aggregation using the aggregation framework
- Функция MongoCollection::aggregateCursor() - Execute an aggregation pipeline command and retrieve results through a cursor
- Функция MongoCollection::batchInsert() - Inserts multiple documents into this collection
- Функция MongoCollection::__construct() - Creates a new collection
- Функция MongoCollection::count() - Counts the number of documents in this collection
- Функция MongoCollection::createDBRef() - Creates a database reference
- Функция MongoCollection::createIndex() - Creates an index on the specified field(s) if it does not already exist.
- Функция MongoCollection::deleteIndex() - Deletes an index from this collection
- Функция MongoCollection::deleteIndexes() - Delete all indices for this collection
- Функция MongoCollection::distinct() - Retrieve a list of distinct values for the given key across a collection.
- Функция MongoCollection::drop() - Drops this collection
- Функция MongoCollection::ensureIndex() - Creates an index on the specified field(s) if it does not already exist.
- MongoCollection::find
- Функция MongoCollection::findAndModify() - Update a document and return it
- Функция MongoCollection::findOne() - Queries this collection, returning a single element
- Функция MongoCollection::__get() - Gets a collection
- Функция MongoCollection::getDBRef() - Fetches the document pointed to by a database reference
- Функция MongoCollection::getIndexInfo() - Returns information about indexes on this collection
- Функция MongoCollection::getName() - Returns this collection's name
- Функция MongoCollection::getReadPreference() - Get the read preference for this collection
- Функция MongoCollection::getSlaveOkay() - Get slaveOkay setting for this collection
- Функция MongoCollection::getWriteConcern() - Get the write concern for this collection
- Функция MongoCollection::group() - Performs an operation similar to SQL's GROUP BY command
- Функция MongoCollection::insert() - Inserts a document into the collection
- Функция MongoCollection::parallelCollectionScan() - Returns an array of cursors to iterator over a full collection in parallel
- Функция MongoCollection::remove() - Remove records from this collection
- Функция MongoCollection::save() - Saves a document to this collection
- Функция MongoCollection::setReadPreference() - Set the read preference for this collection
- Функция MongoCollection::setSlaveOkay() - Change slaveOkay setting for this collection
- Функция MongoCollection::setWriteConcern() - Set the write concern for this database
- Функция MongoCollection::toIndexString() - Converts keys specifying an index to its identifying string
- Функция MongoCollection::__toString() - String representation of this collection
- Функция MongoCollection::update() - Update records based on a given criteria
- Функция MongoCollection::validate() - Validates this collection
Коментарии
The statement
<?php
$c->ensureIndex(array('x' => 1), array("unique" => true));
?>
will prevent a document with a duplicate key ('x') from being added to the connection, but will not throw an exception. To cause an exception to be thrown, use the "safe"=>true option in the insert statement.
Ensuring a text index, needed by text search command.
<?php
$collection->ensureIndex(
array(
'title' => 'text',
'desc' => 'text',
),
array(
'name' => 'ExampleTextIndex',
'weights' => array(
'title' => 100,
'desc' => 30,
)
)
);