MongoCollection::createIndex

(PECL mongo >=1.5.0)

MongoCollection::createIndex Creates an index on the specified field(s) if it does not already exist

説明

public MongoCollection::createIndex ( array $keys [, array $options = array() ] ) : bool

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).

注意:

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.

パラメータ

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. We pass all given options straight to the server, but a non-exhaustive list of currently available options include:

  • "unique"

    TRUE を指定すると、一意なインデックスを作ります。デフォルト値は FALSE です。このオプションを使えるのは、昇順もしくは降順のインデックスだけです。

    注意:

    MongoDB がフィールドをインデックスするとき、もしそのフィールドに値を含まないドキュメントがあれば、NULL 値をインデックスします。このフィールドを含まないドキュメントが複数あった場合、一意なインデックスは、最初に出現したドキュメント以外を受け付けません。これを防ぐには "sparse" オプションを使います。このオプションを指定すれば、インデックス対象のフィールドが存在しないドキュメントはインデックスしなくなります。

  • "sparse"

    TRUE を指定すると、疎なインデックスを作ります。これは、指定したフィールドを含むドキュメントだけをインデックスします。デフォルト値は FALSE です。

  • "expireAfterSeconds"

    このオプションの値に指定するのは、ドキュメントを有効期限切れとみなしてコレクションから自動削除するまでの秒数です。このオプションが使えるのは、単一フィールドインデックスで、フィールドに MongoDate の値を含む場合のみです。

    注意:

    この機能が使えるのは、MongoDB 2.2 以降です。詳細は » Expire Data from Collections by Setting TTL を参照ください。

  • "name"

    オプションの、インデックスを一意に特定するための名前。

    注意:

    ドライバーがデフォルトで生成するインデックス名は、インデックスのフィールドと、並び順あるいは型に基づくものです。たとえば、複合インデックス array("x" => 1, "y" => -1) の名前は "x_1_y_-1" であり、地理空間インデックス array("loc" => "2dsphere") の名前は "loc_2dsphere" となります。多数のフィールドからなるインデックスの場合、自動生成される名前が MongoDB の » インデックス名の制限 を超えてしまう可能性があります。"name" オプションは、そんな場合に短い名前を用意するときなどに使えます。

  • "background"

    Builds the index in the background so that building an index does not block other database activities. Specify TRUE to build in the background. The default value is FALSE.

    警告

    Prior to MongoDB 2.6.0, index builds on secondaries were executed as foreground operations, irrespective of this option. See » Building Indexes with Replica Sets for more information.

  • "socketTimeoutMS"

    このオプションは、ソケット通信の制限時間を、ミリ秒単位で指定します。この時間内にサーバーからの反応がなければ、MongoCursorTimeoutException をスローします。この場合、サーバー側で書き込み処理が行われたのかどうかを判断できなくなります。-1 を指定すると、永遠にブロックします。MongoClient のデフォルト値は 30000 (30 秒) です。

The following option may be used with MongoDB 2.6+:

  • "maxTimeMS"

    サーバー上で操作を行う累積時間の制限 (アイドル時間を含まない) を、ミリ秒単位で指定します。この時間内にサーバー側の操作が完了しなければ、MongoExecutionTimeoutException をスローします。

The following options may be used with MongoDB versions before 2.8:

  • "dropDups"

    TRUE を指定すると、一意なインデックスを強制的に作成します。このとき、コレクション内でキーの値が重複してしまう可能性があります。MongoDB は最初に出現したキーをインデックスし、それ以降に出現する同じキーのすべてのドキュメントを削除します。デフォルト値は FALSE です。

    警告

    "dropDups" はデータベースのデータを削除することがあるので、使う際には十分な注意が必要です。

    注意:

    このオプションは、MongoDB 2.8 以降には対応していません。コレクションに値の重複がある場合は、インデックスの作成に失敗します。

The following options may be used with MongoDB versions before 2.6:

  • "w"

    WriteConcerns を参照ください。MongoClient でのデフォルト値は 1 です。

  • "wTimeoutMS"

    このオプションは、書き込み確認を待つ制限時間をミリ秒単位で指定します。これが書き込み操作に適用されるのは、"w"1 より大きい場合のみです。というのも、タイムアウトはレプリケーションに関する機能だからです。この時間内に書き込み確認ができなかった場合は MongoCursorException をスローします。0 を指定すると、永遠にブロックし続けます。MongoClient でのデフォルトは 10000 ミリ秒 (10 秒) です。

The following options are deprecated and should no longer be used:

  • "safe"

    非推奨。write concernw オプションを使いましょう。

  • "timeout"

    非推奨。"socketTimeoutMS" のエイリアス。

  • "wtimeout"

    廃止予定。"wTimeoutMS" のエイリアスです。

返り値

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().

エラー / 例外

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.

"w" オプションが設定されていて書き込みが失敗した場合に MongoCursorException をスローします。

"w" オプションの値が 1 より大きく設定されていて、操作の完了までの時間が MongoCursor::$timeout ミリ秒をこえた場合に MongoCursorTimeoutException をスローします。サーバー上での操作は止めません。これはクライアント側でのタイムアウトです。MongoCollection::$wtimeout はミリ秒です。

例1 MongoCollection::createIndex() example

<?php

$c 
= new MongoCollection($db'foo');

// create an index on 'x' ascending
$c->createIndex(array('x' => 1));

// create a unique index on 'y'
$c->createIndex(array('y' => 1), array('unique' => true));

// create a compound index on 'za' ascending and 'zb' descending
$c->createIndex(array('za' => 1'zb' => -1));

?>

例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
->createIndex(array('loc' => '2dsphere'));

?>

例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->createIndex(array('username' => 1), array('unique' => 1));

/* MongoDB will one of the conflicting documents and allow the unique index to
 * be created.
 */
$collection->createIndex(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'));

?>

参考