Example usage for com.mongodb DBCollection createIndex

List of usage examples for com.mongodb DBCollection createIndex

Introduction

In this page you can find the example usage for com.mongodb DBCollection createIndex.

Prototype

public void createIndex(final DBObject keys, final DBObject options) 

Source Link

Document

Creates an index on the field specified, if that index does not already exist.

Usage

From source file:com.redhat.lightblue.metadata.mongo.MongoMetadata.java

License:Open Source License

private void createUpdateEntityInfoIndexes(EntityInfo ei) {
    LOGGER.debug("createUpdateEntityInfoIndexes: begin");

    Indexes indexes = ei.getIndexes();//w  ww. j  a v  a 2 s .  c om

    MongoDataStore ds = (MongoDataStore) ei.getDataStore();
    DB entityDB = dbResolver.get(ds);
    DBCollection entityCollection = entityDB.getCollection(ds.getCollectionName());
    Error.push("createUpdateIndex");
    try {
        List<DBObject> existingIndexes = entityCollection.getIndexInfo();
        LOGGER.debug("Existing indexes: {}", existingIndexes);
        for (Index index : indexes.getIndexes()) {
            boolean createIx = true;
            LOGGER.debug("Processing index {}", index);

            for (DBObject existingIndex : existingIndexes) {
                if (indexFieldsMatch(index, existingIndex) && indexOptionsMatch(index, existingIndex)) {
                    LOGGER.debug("Same index exists, not creating");
                    createIx = false;
                    break;
                }
            }

            if (createIx) {
                for (DBObject existingIndex : existingIndexes) {
                    if (indexFieldsMatch(index, existingIndex) && !indexOptionsMatch(index, existingIndex)) {
                        LOGGER.debug("Same index exists with different options, dropping index:{}",
                                existingIndex);
                        // Changing index options, drop the index using its name, recreate with new options
                        entityCollection.dropIndex(existingIndex.get(LITERAL_NAME).toString());
                    }
                }
            }

            if (createIx) {
                DBObject newIndex = new BasicDBObject();
                for (SortKey p : index.getFields()) {
                    newIndex.put(p.getField().toString(), p.isDesc() ? -1 : 1);
                }
                BasicDBObject options = new BasicDBObject("unique", index.isUnique());
                if (index.getName() != null && index.getName().trim().length() > 0) {
                    options.append(LITERAL_NAME, index.getName().trim());
                }
                LOGGER.debug("Creating index {} with options {}", newIndex, options);
                entityCollection.createIndex(newIndex, options);
            }
        }
    } catch (MongoException me) {
        LOGGER.error("createUpdateEntityInfoIndexes: {}", ei);
        throw Error.get(MongoMetadataConstants.ERR_ENTITY_INDEX_NOT_CREATED, me.getMessage());
    } finally {
        Error.pop();
    }

    LOGGER.debug("createUpdateEntityInfoIndexes: end");
}

From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java

License:Open Source License

private void createUpdateEntityInfoIndexes(EntityInfo ei, Metadata md) {
    LOGGER.debug("createUpdateEntityInfoIndexes: begin");

    Indexes indexes = ei.getIndexes();/*from  w w  w. j  a  v  a 2  s .  co m*/

    MongoDataStore ds = (MongoDataStore) ei.getDataStore();
    DB entityDB = dbResolver.get(ds);
    DBCollection entityCollection = entityDB.getCollection(ds.getCollectionName());
    Error.push("createUpdateIndex");
    try {
        List<DBObject> existingIndexes = entityCollection.getIndexInfo();
        LOGGER.debug("Existing indexes: {}", existingIndexes);

        // This is how index creation/modification works:
        //  - The _id index will remain untouched.
        //  - If there is an index with name X in metadata, find the same named index, and compare
        //    its fields/flags. If different, drop and recreate. Drop all indexes with the same field signature.
        //
        //  - If there is an index with null name in metadata, see if there is an index with same
        //    fields and flags. If so, no change. Otherwise, create index. Drop all indexes with the same field signature.
        List<Index> createIndexes = new ArrayList<>();
        List<DBObject> dropIndexes = new ArrayList<>();
        List<DBObject> foundIndexes = new ArrayList<>();
        for (Index index : indexes.getIndexes()) {
            if (!isIdIndex(index)) {
                if (index.getName() != null && index.getName().trim().length() > 0) {
                    LOGGER.debug("Processing index {}", index.getName());
                    DBObject found = null;
                    for (DBObject existingIndex : existingIndexes) {
                        if (index.getName().equals(existingIndex.get("name"))) {
                            found = existingIndex;
                            break;
                        }
                    }
                    if (found != null) {
                        foundIndexes.add(found);
                        // indexFieldsMatch will handle checking for hidden versions of the index
                        if (indexFieldsMatch(index, found) && indexOptionsMatch(index, found)) {
                            LOGGER.debug("{} already exists", index.getName());
                        } else {
                            LOGGER.debug("{} modified, dropping and recreating index", index.getName());
                            existingIndexes.remove(found);
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    } else {
                        LOGGER.debug("{} not found, checking if there is an index with same field signature",
                                index.getName());
                        found = findIndexWithSignature(existingIndexes, index);
                        if (found == null) {
                            LOGGER.debug("{} not found, creating", index.getName());
                            createIndexes.add(index);
                        } else {
                            LOGGER.debug("There is an index with same field signature as {}, drop and recreate",
                                    index.getName());
                            foundIndexes.add(found);
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    }
                } else {
                    LOGGER.debug("Processing index with fields {}", index.getFields());
                    DBObject found = findIndexWithSignature(existingIndexes, index);
                    if (found != null) {
                        foundIndexes.add(found);
                        LOGGER.debug("An index with same keys found: {}", found);
                        if (indexOptionsMatch(index, found)) {
                            LOGGER.debug("Same options as well, not changing");
                        } else {
                            LOGGER.debug("Index with different options, drop/recreate");
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    } else {
                        LOGGER.debug("Creating index with fields {}", index.getFields());
                        createIndexes.add(index);
                    }
                }
            }
        }
        // Any index in existingIndexes but not in foundIndexes should be deleted as well
        for (DBObject index : existingIndexes) {
            boolean found = false;
            for (DBObject x : foundIndexes) {
                if (x == index) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                for (DBObject x : dropIndexes) {
                    if (x == index) {
                        found = true;
                        break;
                    }
                }
                if (!found && !isIdIndex(index)) {
                    LOGGER.warn("Dropping index {}", index.get("name"));
                    entityCollection.dropIndex(index.get("name").toString());
                }
            }
        }
        for (DBObject index : dropIndexes) {
            LOGGER.warn("Dropping index {}", index.get("name"));
            entityCollection.dropIndex(index.get("name").toString());
        }
        // we want to run in the background if we're only creating indexes (no field generation)
        boolean hidden = false;
        // fieldMap is <canonicalPath, hiddenPath>
        List<Path> fields = new ArrayList<>();
        for (Index index : createIndexes) {
            DBObject newIndex = new BasicDBObject();
            for (IndexSortKey p : index.getFields()) {
                Path field = p.getField();
                if (p.isCaseInsensitive()) {
                    fields.add(p.getField());
                    field = DocTranslator.getHiddenForField(field);
                    // if we have a case insensitive index, we want the index creation operation to be blocking
                    hidden = true;
                }
                newIndex.put(ExpressionTranslator.translatePath(field), p.isDesc() ? -1 : 1);
            }
            BasicDBObject options = new BasicDBObject("unique", index.isUnique());
            // if index is unique and non-partial, also make it a sparse index, so we can have non-required unique fields
            options.append("sparse", index.isUnique()
                    && !index.getProperties().containsKey(PARTIAL_FILTER_EXPRESSION_OPTION_NAME));
            if (index.getName() != null && index.getName().trim().length() > 0) {
                options.append("name", index.getName().trim());
            }
            options.append("background", true);
            // partial index
            if (index.getProperties().containsKey(PARTIAL_FILTER_EXPRESSION_OPTION_NAME)) {
                try {
                    @SuppressWarnings("unchecked")
                    DBObject filter = new BasicDBObject((Map<String, Object>) index.getProperties()
                            .get(PARTIAL_FILTER_EXPRESSION_OPTION_NAME));
                    options.append(PARTIAL_FILTER_EXPRESSION_OPTION_NAME, filter);
                } catch (ClassCastException e) {
                    throw new RuntimeException("Index property " + PARTIAL_FILTER_EXPRESSION_OPTION_NAME
                            + " needs to be a mongo query in json format", e);
                }
            }
            LOGGER.debug("Creating index {} with options {}", newIndex, options);
            LOGGER.warn("Creating index {} with fields={}, options={}", index.getName(), index.getFields(),
                    options);
            entityCollection.createIndex(newIndex, options);
        }
        if (hidden) {
            LOGGER.info("Executing post-index creation updates...");
            // case insensitive indexes have been updated or created. recalculate all hidden fields
            Thread pop = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        populateHiddenFields(ei, md, fields);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            pop.start();

            // TODO: remove hidden fields on index deletions? Worth it?
        }
    } catch (MongoException me) {
        throw Error.get(MongoCrudConstants.ERR_ENTITY_INDEX_NOT_CREATED, me.getMessage());
    } catch (Exception e) {
        throw analyzeException(e, MetadataConstants.ERR_ILL_FORMED_METADATA);
    } finally {
        Error.pop();
    }
    LOGGER.debug("createUpdateEntityInfoIndexes: end");
}

From source file:com.restfeel.sample.data.SampleDataGenerator.java

License:Apache License

private void addIndexEntityAuth() {
    DBCollection dbCollectionAuth = mongoTemplate.getCollection("EntityAuth");
    dbCollectionAuth.createIndex(new BasicDBObject("expireAt", 1), new BasicDBObject("expireAfterSeconds", 0));
}

From source file:com.softinstigate.restheart.db.CollectionDAO.java

License:Open Source License

private static void initDefaultIndexes(DBCollection coll) {
    coll.createIndex(new BasicDBObject("_id", 1).append("_etag", 1), new BasicDBObject("name", "_id_etag_idx"));
    coll.createIndex(new BasicDBObject("_etag", 1), new BasicDBObject("name", "_etag_idx"));
    coll.createIndex(new BasicDBObject("_created_on", 1), new BasicDBObject("name", "_created_on_idx"));
}

From source file:de.taimos.dvalin.mongo.ChangelogUtil.java

License:Apache License

/**
 * adds a TTL index to the given collection. The TTL must be a positive integer.
 *
 * @param collection the collection to use for the TTL index
 * @param field      the field to use for the TTL index
 * @param ttl        the TTL to set on the given field
 * @throws IllegalArgumentException if the TTL is less or equal 0
 *//*from  w  w  w  .  ja  v  a 2  s  . c om*/
public static void addTTLIndex(DBCollection collection, String field, int ttl) {
    if (ttl <= 0) {
        throw new IllegalArgumentException("TTL must be positive");
    }
    collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject("expireAfterSeconds", ttl));
}

From source file:de.taimos.dvalin.mongo.ChangelogUtil.java

License:Apache License

/**
 * Add an index on the given collection and field
 *
 * @param collection the collection to use for the index
 * @param field      the field to use for the index
 * @param asc        the sorting direction. <code>true</code> to sort ascending; <code>false</code> to sort descending
 * @param background iff <code>true</code> the index is created in the background
 *///  www .  j a  v  a2s .c  o m
public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {
    int dir = (asc) ? 1 : -1;
    collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject("background", background));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Creates an index on a set of fields, if one does not already exist on the specified collection.
 * Indexes created with this method are created in the background and could stores unique elements.
 * @param fields - fields that are used to index the elements
 * @param collection - collection where the index is created
 * @param descending - (optional) sort the elements of the index in descending order
 *//*from   w ww .j  a  va 2  s . c  om*/
public void createIndex(final List<String> fields, final String collection, final boolean unique,
        final boolean descending) {
    checkArgument(fields != null && !fields.isEmpty(), "Uninitialized or invalid fields");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    dbcol.createIndex(new BasicDBObject(toMap(fields, new Function<String, Integer>() {
        @Override
        public Integer apply(final String field) {
            return descending ? -1 : 1;
        }
    })), new BasicDBObject(unique ? ImmutableMap.of("unique", true, "background", true)
            : ImmutableMap.of("background", true)));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Creates a new geospatial index in a collection. Indexes are created in the background.
 * @param field - field that is used to index the elements
 * @param collection - collection where the index is created
 *//*from  w  w  w. ja  v  a  2s.c om*/
public void createGeospatialIndex(final String field, final String collection) {
    checkArgument(isNotBlank(field), "Uninitialized or invalid field");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    dbcol.createIndex(new BasicDBObject(field, "2dsphere"), new BasicDBObject("background", true));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Creates a text index in a collection. Text indexes are created using English as the default language.
 * @param fields - fields that are used to index the elements
 * @param collection - collection where the index is created
 *///from   w w  w .j  av  a  2  s  .c om
public void createTextIndex(final List<String> fields, final String collection) {
    checkArgument(fields != null && !fields.isEmpty(), "Uninitialized or invalid fields");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    dbcol.createIndex(new BasicDBObject(toMap(fields, new Function<String, String>() {
        @Override
        public String apply(final String field) {
            return "text";
        }
    })), new BasicDBObject("default_language", "english").append("name", collection + ".text_idx"));
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java

License:EUPL

/**
 * Creates a sparse, non unique, index, if one does not already exist on the specified collection.
 * Indexes created with this method are created in the background. <strong>Note:</strong> Do NOT use compound indexes to
 * create an sparse index, since the results are unexpected.
 * @param field - field that is used to index the elements
 * @param collection - collection where the index is created
 * @param descending - (optional) sort the elements of the index in descending order
 * @see <a href="http://docs.mongodb.org/manual/core/index-sparse/">MongoDB: Sparse Indexes</a>
 *//*from   w  ww  .j ava  2s .c om*/
public void createSparseIndex(final String field, final String collection, final boolean descending) {
    checkArgument(isNotBlank(field), "Uninitialized or invalid field");
    checkArgument(isNotBlank(collection), "Uninitialized or invalid collection");
    final DB db = client().getDB(CONFIG_MANAGER.getDbName());
    final DBCollection dbcol = db.getCollection(collection);
    dbcol.createIndex(new BasicDBObject(field, descending ? -1 : 1),
            new BasicDBObject(ImmutableMap.of("background", true, "sparse", true)));
}