Forces creation of an index on a set of fields, if one does not already exist.

@param keys    The keys to index
@param options The options
@throws MongoException If an error occurred
962985
public void createIndex(DBObject keys, DBObject options) throws MongoException {
        dbCollection.createIndex(keys, options);
    }
162014
def _create_indexes(self):
        """"""
        # WARNING: The collection will be locked during the index
        # creation. If the collection has a large number of
        # documents in it, the operation can take a long time.

        # TODO: The creation of indexes can be moved to a Django
        # management command or equivalent. There is also an option to
        # run the indexing on the background, without locking.
        self.collection.ensure_index([('time', pymongo.DESCENDING)])
        self.collection.ensure_index('name')
16064
public function createIndexes(array $indexes, array $options = [])
    {
        if (empty($indexes)) {
            throw new InvalidArgumentException('$indexes array cannot be empty.');
        }

        $compiledIndexes = array_map(function (Index $index) {
            return $index->toArray();
        }, $indexes);

        $this->executeCommand(
            ['createIndexes' => $this->collectionName, 'indexes' => $compiledIndexes],
            $options
        );

        return array_map(function (Index $index) {
            return $index->getName();
        }, $indexes);
    }
939453
private function _createIndex(array $columnNames, $indexName, $isUnique, $isPrimary, array $flags = [], array $options = [])
    {
        if (preg_match('(([^a-zA-Z0-9_]+))', $this->normalizeIdentifier($indexName))) {
            throw SchemaException::indexNameInvalid($indexName);
        }

        foreach ($columnNames as $columnName) {
            if (! $this->hasColumn($columnName)) {
                throw SchemaException::columnDoesNotExist($columnName, $this->_name);
            }
        }

        return new Index($indexName, $columnNames, $isUnique, $isPrimary, $flags, $options);
    }
695321
private function indexOptionsAreMissing(array $mongoIndexOptions, array $documentIndexOptions) : bool
    {
        foreach (self::ALLOWED_MISSING_INDEX_OPTIONS as $option) {
            unset($mongoIndexOptions[$option], $documentIndexOptions[$option]);
        }

        return array_diff_key($mongoIndexOptions, $documentIndexOptions) !== [] || array_diff_key($documentIndexOptions, $mongoIndexOptions) !== [];
    }
918409
public void setIndexNames(java.util.Collection<String> indexNames) {
        if (indexNames == null) {
            this.indexNames = null;
            return;
        }

        this.indexNames = new java.util.ArrayList<String>(indexNames);
    }
826449
public function setShardKey(array $keys, array $options = []) : void
    {
        if ($this->inheritanceType === self::INHERITANCE_TYPE_SINGLE_COLLECTION && $this->shardKey !== []) {
            throw MappingException::shardKeyInSingleCollInheritanceSubclass($this->getName());
        }

        if ($this->isEmbeddedDocument) {
            throw MappingException::embeddedDocumentCantHaveShardKey($this->getName());
        }

        foreach (array_keys($keys) as $field) {
            if (! isset($this->fieldMappings[$field])) {
                continue;
            }

            if (in_array($this->fieldMappings[$field]['type'], ['many', 'collection'])) {
                throw MappingException::noMultiKeyShardKeys($this->getName(), $field);
            }

            if ($this->fieldMappings[$field]['strategy'] !== static::STORAGE_STRATEGY_SET) {
                throw MappingException::onlySetStrategyAllowedInShardKey($this->getName(), $field);
            }
        }

        $this->shardKey = [
            'keys' => array_map(static function ($value) {
                if ($value === 1 || $value === -1) {
                    return $value;
                }
                if (is_string($value)) {
                    $lower = strtolower($value);
                    if ($lower === 'asc') {
                        return 1;
                    }

                    if ($lower === 'desc') {
                        return -1;
                    }
                }
                return $value;
            }, $keys),
            'options' => $options,
        ];
    }
1336356
def create_index(self, key, reindex=True, sparse=False):
        
        warnings.warn('Index support is currently very alpha and is not guaranteed')
        if isinstance(key, (list, tuple)):
            index_name = ','.join(key)
            index_columns = ', '.join('%s text' % f for f in key)
        else:
            index_name = key
            index_columns = '%s text' % key

        table_name = '[%s{%s}]' % (self.name, index_name)
        reindex = reindex or not self._object_exists('table', table_name)

        # Create a table store for the index data
        self.db.execute("""
            create table if not exists {table} (
                id integer primary key,
                {columns},
                foreign key(id) references {collection}(id) on delete cascade on update cascade
            )
        """.format(
            table=table_name,
            collection=self.name,
            columns=index_columns
        ))

        # Create the index
        self.db.execute("""
            create index if not exists [idx.{collection}{{index}}] on {table}({index})
        """.format(
            collection=self.name,
            index=index_name,
            table=table_name,
        ))

        if reindex:
            self.reindex(key)
784047
function getIndexes(done, results) {
  var client = results.client;
  var ns = mongodbNS(results.namespace);
  client
    .db(ns.database)
    .collection(ns.collection)
    .indexes(function(err, indexes) {
      if (err) {
        done(err);
      }
      // add ns field to each index
      _.each(indexes, function(idx) {
        idx.ns = ns.ns;
      });
      done(null, indexes);
    });
}
1243895
function MongoStore(options) {
        options = options || {};

        for (var property in defaultOptions) {
            if (defaultOptions.hasOwnProperty(property)) {
                if (!options.hasOwnProperty(property) || (typeof defaultOptions[property] !== typeof options[property]))
                    options[property] = defaultOptions[property];
            }
        }

        Store.call(this, options.store);

        var dbProperties = ["name", "prefix", "servers", "credentials", "URLParam", "extraParam"];
        var dbPropertiesLen = dbProperties.length;
        var dbOptions = {};
        for (var i = 0; i < dbPropertiesLen; i++)
            dbOptions[dbProperties[i]] = options[dbProperties[i]];

        this.mongo = new Mongo(dbOptions);
        this.mongo.ensureIndex(options.collection, {expires: 1}, {expireAfterSeconds: 0}, function (err, result) {
            if (err)
                throw new Error('Error setting TTL index on collection : ' + options.collection + ' <' + err + '>');
        });

        this._options = {
            "collection": options.collection,
            "stringify": options.stringify,
            "expireAfter": options.expireAfter
        };
    }
891112
public void add(List<Key> keys){
    if(keys == null) {
      throw new IllegalArgumentException("ArrayList<Key> may not be null");
    }

    for(Key key: keys) {
      add(key);
    }
  }
891136
public void add(DOCUMENT doc) {
      if (doc != null) {
         documents.add(doc);
         int id = documents.size() - 1;
         for (KEY key : documentMapper.apply(doc)) {
            index.put(key, id);
         }
      }
   }
1318772
def ensure_indexes(self):
        """"""
        for collection_name in INDEXES:
            existing_indexes = self.indexes(collection_name)
            indexes = INDEXES[collection_name]
            for index in indexes:
                index_name = index.document.get('name')
                if index_name in existing_indexes:
                    logger.debug("Index exists: %s" % index_name)
                    self.db[collection_name].drop_index(index_name)
            logger.info("creating indexes for collection {0}: {1}".format(
                collection_name,
                ', '.join([index.document.get('name') for index in indexes]),
                )
            )
            self.db[collection_name].create_indexes(indexes)
266714
public void setChangedNodes( Set<NodeKey> keys ) {
        if (keys != null) {
            this.nodeKeys = Collections.unmodifiableSet(new HashSet<NodeKey>(keys));
        }
    }
573642
void addDocuments(final Document[] docs) throws IOException
   {
      final IndexWriter writer = getIndexWriter();

      IOException ioExc = null;
      try
      {
         for (Document doc : docs)
         {
            try
            {
               writer.addDocument(doc);
            }
            catch (Throwable e) //NOSONAR
            {
               if (ioExc == null)
               {
                  if (e instanceof IOException)
                  {
                     ioExc = (IOException)e;
                  }
                  else
                  {
                     ioExc = Util.createIOException(e);
                  }
               }

               log.warn("Exception while inverting document", e);
            }
         }
      }
      finally
      {
         invalidateSharedReader();
      }

      if (ioExc != null)
      {
         throw ioExc;
      }
   }
149802
public void setKeys(java.util.Collection<java.util.Map<String, AttributeValue>> keys) {
        if (keys == null) {
            this.keys = null;
            return;
        }

        this.keys = new java.util.ArrayList<java.util.Map<String, AttributeValue>>(keys);
    }
297455
protected void setIndexedProperty(Object bean, String name, int[] indexes, Object value, FormMappingOption option) { // e.g. sea[0]
        final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(bean.getClass());
        if (!beanDesc.hasPropertyDesc(name)) {
            return;
        }
        final PropertyDesc pd = beanDesc.getPropertyDesc(name);
        if (!pd.isWritable()) {
            return;
        }
        if (value.getClass().isArray() && Array.getLength(value) > 0) {
            value = Array.get(value, 0);
        }
        final Class<?> propertyType = pd.getPropertyType();
        if (propertyType.isArray()) {
            Object array = pd.getValue(bean);
            final Class<?> elementType = getArrayElementType(propertyType, indexes.length);
            if (array == null) {
                int[] newIndexes = new int[indexes.length];
                newIndexes[0] = indexes[0] + 1;
                array = Array.newInstance(elementType, newIndexes);
            }
            array = expand(array, indexes, elementType);
            pd.setValue(bean, array);
            setArrayValue(array, indexes, value);
        } else { // e.g. List, ImmutableList, MutableList
            // process of your collections should be first because MutableList is java.util.List 
            final Optional<FormYourCollectionResource> yourCollection = findListableYourCollection(pd, option);
            if (yourCollection.isPresent()) { // e.g. ImmutableList, MutableList
                doSetIndexedPropertyListable(bean, name, indexes, value, beanDesc, pd, option, newList -> {
                    @SuppressWarnings("unchecked")
                    final List<Object> filtered = (List<Object>) yourCollection.get().getYourCollectionCreator().apply(newList);
                    return filtered;
                });
            } else if (List.class.isAssignableFrom(propertyType)) {
                doSetIndexedPropertyListable(bean, name, indexes, value, beanDesc, pd, option, Function.identity());
            } else {
                throwIndexedPropertyNotListArrayException(beanDesc, pd);
            }
        }
    }