ensureIndex() public method

Creates an index on the given field(s), or does nothing if the index already exists
Deprecation: Use MongoCollection::createIndex() instead.
public ensureIndex ( array $keys, array $options = [] ) : array
$keys array Field or fields to use as index.
$options array [optional] This parameter is an associative array of the form array("optionname" => , ...).
return array Returns the database response.
Esempio n. 1
0
 public function __construct()
 {
     $mongo = new Mongo();
     $mongoDb = $mongo->selectDB('ContactsManager');
     $this->contactsManagerCollection = new MongoCollection($mongoDb, 'Contact');
     $this->contactsManagerCollection->ensureIndex(array('email' => 1), array('unique' => true, 'dropDups' => true));
 }
 /**
  * Construct a new instance of MongoCache.
  *
  * @param \MongoCollection $collection        The collection containing the cached data.
  * @param integer          $defaultTimeToLive The default time to live in seconds.
  *
  * @throws \RuntimeException Throw if mongo extension is not loaded.
  * @throws \InvalidArgumentException Throw if $defaultTimeToLive is not an integer between 0 and 86400.
  */
 public function __construct(\MongoCollection $collection, $defaultTimeToLive = CacheInterface::MAX_TTL)
 {
     if (!extension_loaded('mongo')) {
         throw new \RuntimeException('The mongo extension is required for MongoCache');
     }
     $this->setDefaultTTL($defaultTimeToLive);
     $this->collection = $collection;
     $this->collection->ensureIndex(['expires' => 1], ['expireAfterSeconds' => 0, 'background' => true]);
 }
 /**
  * Connects to mongodb.
  *
  * @return \MongoCollection
  */
 public function connect()
 {
     if (!$this->collection) {
         $client = new \MongoClient($this->server);
         $db = $client->selectDB($this->db);
         $this->collection = $db->selectCollection('mc_info_sms_subscription_low_balance_reminder_logs');
         $this->collection->ensureIndex(array('mobile' => 1), array('unique' => true));
     }
     return $this->collection;
 }
 /**
  * Connects to mongodb.
  *
  * @return \MongoCollection
  */
 public function connect()
 {
     if (!$this->collection) {
         $client = new \MongoClient($this->server);
         $db = $client->selectDB($this->db);
         $this->collection = $db->selectCollection('mc_recharge_card_profiles');
         $this->collection->ensureIndex(array('uniqueness' => 1), array('unique' => true));
     }
     return $this->collection;
 }
 /**
  * Connects to mongodb.
  *
  * @return \MongoCollection
  */
 public function connect()
 {
     if (!$this->collection) {
         $client = new \MongoClient($this->server);
         $db = $client->selectDB($this->db);
         $this->collection = $db->selectCollection('mc_invitation_cards');
         $this->collection->ensureIndex(array('code' => 1), array('unique' => true));
     }
     return $this->collection;
 }
 /**
  * Connects to mongodb.
  *
  * @return \MongoCollection
  */
 public function connect()
 {
     if (!$this->collection) {
         $client = new \MongoClient($this->server);
         $db = $client->selectDB($this->db);
         $this->collection = $db->selectCollection('mc_info_sms_message_links');
         $this->collection->ensureIndex(array('message' => 1), array('unique' => true));
     }
     return $this->collection;
 }
Esempio n. 7
0
 public function __construct($server = 'mongodb://localhost:27017', $db = 'phpconsole', $collection = 'phpconsole')
 {
     $this->mongoClient = new \MongoClient($server);
     if (!$this->mongoClient) {
         throw new \Exception('Unable to connect to MongoDB server');
     }
     $this->mongoCollection = $this->mongoClient->selectCollection($db, $collection);
     if (!$this->mongoCollection) {
         throw new \Exception('Unable to get collection');
     }
     $this->mongoCollection->ensureIndex(array('expireAt' => 1), array('background' => true, 'name' => 'TTL', 'expireAfterSeconds' => 0));
 }
Esempio n. 8
0
 /**
  * Sets up the MongoDB table and
  * initialises the MongoDB connection
  *
  * @param  array  $config  configuration
  * @throws  Cache_Exception
  */
 protected function __construct(array $config)
 {
     parent::__construct($config);
     $database = Arr::get($this->_config, 'database', NULL);
     if ($database === NULL) {
         throw new Cache_Exception('Database path not available in Kohana Cache configuration');
     }
     $this->_client = new MongoClient('mongodb://' . $this->_config['host'] . ':' . $this->_config['port']);
     $this->_database = $this->_client->{$database};
     $this->_collection = $this->_database->{$this->_config['collection']};
     $this->_collection->ensureIndex(array('tags' => 1));
     $this->_collection->ensureIndex(array('lifetime' => 1));
 }
Esempio n. 9
0
 /**
  * @return void
  */
 public function __construct($options)
 {
     if (!extension_loaded('mongo')) {
         \Zend_Cache::throwException('The MongoDB extension must be loaded for using this backend !');
     }
     parent::__construct($options);
     // Merge the options passed in; overridding any default options
     $this->_options = array_merge($this->_options, $options);
     $this->_conn = new \MongoClient($this->getServerConnectionUrl());
     $this->_db = $this->_conn->selectDB($this->_options['dbname']);
     $this->_collection = $this->_db->selectCollection($this->_options['collection']);
     $this->_collection->ensureIndex(array('t' => 1), array('background' => true));
     $this->_collection->ensureIndex(array('expires_at' => 1), array('background' => true));
 }
Esempio n. 10
0
 /**
  * @return void
  */
 public function __construct($options)
 {
     if (!extension_loaded('mongo') && !extension_loaded('mongodb')) {
         \Zend_Cache::throwException('The MongoDB extension must be loaded for using this backend !');
     }
     parent::__construct($options);
     // Merge the options passed in; overridding any default options
     $this->_options = array_merge($this->_options, $options);
     $this->_conn = new \MongoClient('mongodb://' . $this->_options['host'] . ':' . $this->_options['port'], $this->_options['optional']);
     $this->_db = $this->_conn->selectDB($this->_options['dbname']);
     $this->_collection = $this->_db->selectCollection($this->_options['collection']);
     $this->_collection->ensureIndex(['t' => 1], ['background' => true]);
     $this->_collection->ensureIndex(['expire' => 1], ['background' => true]);
 }
Esempio n. 11
0
 /**
  * Specify an index for the collection.
  *
  * @param  string|array  $columns
  * @param  array         $options
  * @return Blueprint
  */
 public function index($columns = null, $options = [])
 {
     $columns = $this->fluent($columns);
     // Columns are passed as a default array.
     if (is_array($columns) && is_int(key($columns))) {
         // Transform the columns to the required array format.
         $transform = [];
         foreach ($columns as $column) {
             $transform[$column] = 1;
         }
         $columns = $transform;
     }
     $this->collection->ensureIndex($columns, $options);
     return $this;
 }
Esempio n. 12
0
 /**
  * Constructor. Sets the Mongo DB adapter.
  *
  * @param \MongoClient $Mongo     A \MongoClient instance.
  * @param array        $options   Array of options.
  */
 public function __construct(\MongoClient $Mongo, array $options = null)
 {
     // default options
     $this->options['db_name'] = 'apix';
     $this->options['collection_name'] = 'cache';
     $this->options['object_serializer'] = 'php';
     // null, php, json, igBinary.
     // Set the adapter and merge the user+default options
     parent::__construct($Mongo, $options);
     $this->db = $this->adapter->selectDB($this->options['db_name']);
     $this->collection = $this->db->createCollection($this->options['collection_name'], false);
     $this->collection->ensureIndex(array('key' => 1), array('unique' => true, 'dropDups' => true));
     // Using MongoDB TTL collections (MongoDB 2.2+)
     $this->collection->ensureIndex(array('expire' => 1), array('expireAfterSeconds' => 1));
     $this->setSerializer($this->options['object_serializer']);
 }
Esempio n. 13
0
 /**
  * Wrapper method for MongoCollection::ensureIndex().
  *
  * @see http://php.net/manual/en/mongocollection.ensureindex.php
  * @param array $keys
  * @param array $options
  * @return array|boolean
  */
 public function ensureIndex(array $keys, array $options = array())
 {
     $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options;
     $options = isset($options['timeout']) ? $this->convertSocketTimeout($options) : $options;
     $options = isset($options['wtimeout']) ? $this->convertWriteTimeout($options) : $options;
     return $this->mongoCollection->ensureIndex($keys, $options);
 }
Esempio n. 14
0
 /**
  * @param array $index
  */
 public function createIndex($index, $options = [])
 {
     if (!count($options)) {
         $options = ['name' => $this->table . 'TextIndex'];
     }
     $this->collection->ensureIndex($index, $options);
 }
Esempio n. 15
0
 /**
  * Ensure index of correct specification and a unique name whether the specification or name already exist or not.
  * Will not create index if $index is a prefix of an existing index
  *
  * @param array $index index to create in same format as \MongoCollection::ensureIndex()
  *
  * @return void
  *
  * @throws \Exception couldnt create index after 5 attempts
  */
 private function _ensureIndex(array $index)
 {
     //if $index is a prefix of any existing index we are good
     foreach ($this->_collection->getIndexInfo() as $existingIndex) {
         $slice = array_slice($existingIndex['key'], 0, count($index), true);
         if ($slice === $index) {
             return;
         }
     }
     for ($i = 0; $i < 5; ++$i) {
         for ($name = uniqid(); strlen($name) > 0; $name = substr($name, 0, -1)) {
             //creating an index with same name and different spec does nothing.
             //creating an index with same spec and different name does nothing.
             //so we use any generated name, and then find the right spec after we have called, and just go with that name.
             try {
                 $this->_collection->ensureIndex($index, array('name' => $name, 'background' => true));
             } catch (\MongoException $e) {
                 //this happens when the name was too long, let continue
             }
             foreach ($this->_collection->getIndexInfo() as $existingIndex) {
                 if ($existingIndex['key'] === $index) {
                     return;
                 }
             }
         }
     }
     throw new \Exception('couldnt create index after 5 attempts');
 }
Esempio n. 16
0
 /**
  * Create an index.
  *
  * Effectively, just a wrapper around the collections own ensureIndex method.
  *
  * @param array $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.
  * @param array $options
  *   (Optional) An array of options for the index creation.
  *
  * @throws \Vultan\Exception\VultanIndexException
  * @see http://www.php.net/manual/en/mongocollection.createindex.php
  */
 public function createIndex(array $keys, array $options = array())
 {
     try {
         $this->collection->ensureIndex($keys, $options);
     } catch (\MongoException $e) {
         throw new VultanIndexException('Unable to create index: ' . $e->getMessage());
     }
 }
Esempio n. 17
0
 /**
  * Initialises the store instance for use.
  *
  * Once this has been done the cache is all set to be used.
  *
  * @param cache_definition $definition
  * @throws coding_exception
  */
 public function initialise(cache_definition $definition)
 {
     if ($this->is_initialised()) {
         throw new coding_exception('This mongodb instance has already been initialised.');
     }
     $this->database = $this->connection->selectDB($this->databasename);
     $this->definitionhash = $definition->generate_definition_hash();
     $this->collection = $this->database->selectCollection($this->definitionhash);
     $this->collection->ensureIndex(array('key' => 1), array('safe' => $this->usesafe, 'name' => 'idx_key'));
 }
Esempio n. 18
0
 public function loadOrder($id, $field)
 {
     $this->setData(array());
     $this->_tblSales->ensureIndex("order.{$field}");
     $result = $this->_tblSales->findOne(array("order.{$field}" => $id));
     if ($result['_id']) {
         $this->setData($result);
     }
     return $this;
 }
Esempio n. 19
0
 function crearIndiceATablaTemporal($TABLA, $INDICE)
 {
     try {
         $DB = $this->CONEXION->innet;
         $COLECCION = new MongoCollection($DB, "temporal" . $TABLA);
         $COLECCION->ensureIndex($INDICE);
     } catch (Exception $e) {
         $this->LOG->registraLog("Generica", $e->getMessage(), "No es posible crear un indice " . $TABLA);
         return false;
     }
     return true;
 }
 /**
  * @param Schema $schema
  */
 public function postUp(Schema $schema)
 {
     $upgradeHelper = new UpgradeHelper($this->container);
     if ($upgradeHelper->areProductsStoredInMongo()) {
         $database = $upgradeHelper->getMongoInstance();
         $tableHelper = new SchemaHelper($this->container);
         echo "Add index to Version document on column loggetAt...\n";
         $versionCollection = new \MongoCollection($database, $tableHelper->getTableOrCollection('version'));
         $versionCollection->ensureIndex(['loggedAt' => -1], ['background' => true]);
         echo "Done.";
     }
 }
Esempio n. 21
0
 /**
  * 
  * @param Oops_Config|MongoCollection $config
  */
 public function __construct($config = null)
 {
     if ($config instanceof MongoCollection) {
         $this->_collection = $config;
     } else {
         $db = null;
         $coll = null;
         $client = null;
         if ($config instanceof Oops_Config) {
             $config = $config->__toArray();
         }
         if (is_array($config)) {
             if (isset($config['db'])) {
                 $db = $config['db'];
             }
             if (isset($config['collection'])) {
                 $coll = $config['collection'];
             }
             if (isset($config['server'])) {
                 if (isset($config['options'])) {
                     $client = new MongoClient($config['server'], $config['options']);
                 } else {
                     $client = new MongoClient($config['server']);
                 }
             }
         }
         if (!isset($client)) {
             $client = new MongoClient();
         }
         if (!isset($db)) {
             $db = 'cascache';
         }
         if (!isset($coll)) {
             $coll = 'mapstore';
         }
         $this->_collection = $client->{$db}->{$coll};
         $this->_collection->ensureIndex(array('source' => 1));
     }
 }
Esempio n. 22
0
 /**
  * Initialises the store instance for use.
  *
  * Once this has been done the cache is all set to be used.
  *
  * @param cache_definition $definition
  * @throws coding_exception
  */
 public function initialise(cache_definition $definition)
 {
     if ($this->is_initialised()) {
         throw new coding_exception('This mongodb instance has already been initialised.');
     }
     $this->database = $this->connection->selectDB($this->databasename);
     $this->definitionhash = 'm' . $definition->generate_definition_hash();
     $this->collection = $this->database->selectCollection($this->definitionhash);
     $options = array('name' => 'idx_key');
     if ($this->legacymongo) {
         $options['safe'] = $this->usesafe;
     } else {
         $options['w'] = $this->usesafe ? 1 : 0;
     }
     $this->collection->ensureIndex(array('key' => 1), $options);
 }
Esempio n. 23
0
 /**
  * Create indexes based on self::$_index metadata
  *
  * @return \Sokil\Mongo\Collection
  * @throws \Exception
  */
 public function initIndexes()
 {
     // read index definition from collection options
     // if not specified - use defined in property
     $indexDefinition = $this->definition->getOption('index');
     // ensure indexes
     foreach ($indexDefinition as $options) {
         if (empty($options['keys'])) {
             throw new Exception('Keys not specified');
         }
         $keys = $options['keys'];
         unset($options['keys']);
         $this->_mongoCollection->ensureIndex($keys, $options);
     }
     return $this;
 }
 public function testGetIndexInfo()
 {
     $info = $this->object->getIndexInfo();
     $this->assertEquals(count($info), 0);
     $this->object->ensureIndex(array('foo' => 1));
     $this->object->ensureIndex(array('foo' => -1));
     $this->object->ensureIndex(array('bar' => 1, 'baz' => -1));
     $info = $this->object->getIndexInfo();
     $this->assertEquals(4, count($info), json_encode($info));
     $this->assertEquals($info[1]['key']['foo'], 1);
     $this->assertEquals($info[1]['name'], 'foo_1');
     $this->assertEquals($info[2]['key']['foo'], -1);
     $this->assertEquals($info[2]['name'], 'foo_-1');
     $this->assertEquals($info[3]['key']['bar'], 1);
     $this->assertEquals($info[3]['key']['baz'], -1);
     $this->assertEquals($info[3]['name'], 'bar_1_baz_-1');
 }
 /**
  * @param array $tables
  */
 public function loadDevices(&$tables)
 {
     $insert_errors = array();
     $insertcache = array();
     $insertedrows = 0;
     $this->createProcedures();
     // insert records into a new temp table until we know everything is OK
     $temptable = self::$MERGE . self::$DB_TEMP_EXT;
     $this->_dropCollectionIfExists($temptable);
     // create this collection manually since it is fixed
     $this->dbcon->command(array("create" => $temptable, "size" => self::$PREALLOC_SIZE));
     $collection = $this->dbcon->selectCollection($temptable);
     foreach ($tables as $table => $devices) {
         $matcher = $this->getMatcherNameFromTable($table);
         $matcherbatch = array();
         foreach ($devices as $device) {
             $matcherbatch[] = array('deviceID' => $device['id'], 'user_agent' => $device['user_agent'], 'fall_back' => $device['fall_back'], 'match' => preg_match('/^DO_NOT_MATCH/', $device['user_agent']) ? false : true, 'actual_device_root' => isset($device['actual_device_root']) ? $device['actual_device_root'] : '', 'matcher' => $matcher, 'capabilities' => $device);
             $insertedrows++;
         }
         try {
             $collection->batchInsert($matcherbatch);
             $this->numQueries++;
         } catch (Exception $e) {
             $insert_errors[] = 'DB server reported error on id "' . $device['id'] . '": ' . $e->getMessage();
         }
         if (count($insert_errors) > 0) {
             // Roll back changes, and leave the temp table in the DB for manual inspection
             $this->errors = array_merge($this->errors, $insert_errors);
             return false;
         }
     }
     // Commit changes
     $this->_dropCollectionIfExists(self::$MERGE);
     $this->_renameCollection($temptable, self::$MERGE);
     // Enforce Indecies
     $this->mergecoll->ensureIndex(array('deviceID' => 1), array("unique" => true, "dropDups" => true, "background" => true, "safe" => false));
     $this->mergecoll->ensureIndex(array('user_agent' => 1), array("unique" => false, "dropDups" => false, "background" => true, "safe" => false));
     $this->mergecoll->ensureIndex(array('fall_back' => 1), array("unique" => false, "dropDups" => false, "background" => true, "safe" => false));
     $this->mergecoll->ensureIndex(array('matcher' => 1), array("unique" => false, "dropDups" => false, "background" => true, "safe" => false));
     $this->mergecoll->ensureIndex(array('match' => 1), array("unique" => false, "dropDups" => false, "background" => true, "safe" => false));
     return true;
 }
Esempio n. 26
0
 /**
  * 
  */
 public function __construct()
 {
     $this->lang = Translator::getInstance()->getLang();
     $this->collection = MongoCache::getInstance(false)->getMongoDB()->selectCollection('statistics');
     $this->collection->ensureIndex('account');
 }
Esempio n. 27
0
 protected function _call($command, array $arguments = array(), array $values = NULL)
 {
     $start = microtime(true);
     $this->_connected or $this->connect();
     extract($arguments);
     if (isset($collection_name)) {
         $c = new \MongoCollection($this->_db, $collection_name);
     }
     switch ($command) {
         case 'ensure_index':
             $r = $c->ensureIndex($keys, $options);
             break;
         case 'create_collection':
             $r = $this->_db->createCollection($name, $capped, $size, $max);
             break;
         case 'drop_collection':
             $r = $this->_db->dropCollection($name);
             break;
         case 'command':
             $r = $this->_db->command($values);
             break;
         case 'execute':
             $r = $this->_db->execute($code, $args);
             break;
         case 'batch_insert':
             $r = $c->batchInsert($values);
             break;
         case 'count':
             $r = $c->count($query);
             break;
         case 'find_one':
             $r = $c->findOne($query, $fields);
             break;
         case 'find':
             $r = $c->find($query, $fields);
             break;
         case 'group':
             $r = $c->group($keys, $initial, $reduce, $condition);
             break;
         case 'update':
             $r = $c->update($criteria, $values, $options);
             break;
         case 'insert':
             $r = $c->insert($values, $options);
             return $values;
             break;
         case 'remove':
             $r = $c->remove($criteria, $options);
             break;
         case 'save':
             $r = $c->save($values, $options);
             break;
         case 'get_file':
             $r = $this->gridFS()->findOne($criteria);
             break;
         case 'get_files':
             $r = $this->gridFS()->find($query, $fields);
             break;
         case 'set_file_bytes':
             $r = $this->gridFS()->storeBytes($bytes, $extra, $options);
             break;
         case 'set_file':
             $r = $this->gridFS()->storeFile($filename, $extra, $options);
             break;
         case 'remove_file':
             $r = $this->gridFS()->remove($criteria, $options);
             break;
     }
     $this->log($command, $start, $arguments);
     return $r;
 }
 /**
  * @expectedException MongoException 
  */
 public function testIndexNameLen2()
 {
     $this->object->ensureIndex(array("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" => 1));
 }
<?php

require 'vendor/autoload.php';
$secret_key = getenv('SECRET_KEY') ? getenv('SECRET_KEY') : 'Cth4nG3_M3';
$config = getenv('OPENSHIFT_MONGODB_DB_URL') . getenv('OPENSHIFT_APP_NAME');
$client = new MongoClient($config);
$db = $client->selectDB(getenv('OPENSHIFT_APP_NAME'));
$parks = new MongoCollection($db, 'parks');
$result = $parks->ensureIndex(array('pos' => "2d"));
Esempio n. 30
0
 /**
  * ensureIndex.
  */
 public function ensureIndex($keys, array $options = array())
 {
     $this->time->start();
     $return = parent::ensureIndex($keys, $options);
     $time = $this->time->stop();
     $this->log(array('type' => 'ensureIndex', 'keys' => $keys, 'options' => $options, 'time' => $time));
     return $return;
 }