Example usage for com.mongodb DBCollection dropIndex

List of usage examples for com.mongodb DBCollection dropIndex

Introduction

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

Prototype

public void dropIndex(final String indexName) 

Source Link

Document

Drops the index with the given name from this collection.

Usage

From source file:com.andreig.jetty.IndexServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doDelete()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);/*www.ja  va  2s.  com*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    BufferedReader r = null;
    String data = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        data = r.readLine();

    } finally {
        if (r != null)
            r.close();
    }
    if (data == null) {
        error(res, SC_BAD_REQUEST, Status.get("no data"));
        return;
    }

    DBObject o = null;
    try {
        o = (DBObject) JSON.parse(data);
    } catch (JSONParseException e) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    col.dropIndex(o);

    res.setStatus(SC_OK);

}

From source file:com.cyslab.craftvm.rest.mongo.IndexServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);//from   w w  w .j  av a2s.co  m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;
    }

    BufferedReader r = null;
    String data = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        data = r.readLine();

    } finally {
        if (r != null)
            r.close();
    }
    if (data == null) {
        error(res, SC_BAD_REQUEST, Status.get("no data"));
        return;
    }

    DBObject o = null;
    try {
        o = (DBObject) JSON.parse(data);
    } catch (JSONParseException e) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    col.dropIndex(o);

    res.setStatus(SC_OK);

}

From source file:com.ebay.cloud.cms.dal.persistence.MongoExecutor.java

License:Apache License

public static void dropIndex(PersistenceContext context, MetaClass metadata, String indexName) {
    long start = System.currentTimeMillis();
    String msg = "success";
    DBCollection dbCollection = context.getDBCollection(metadata);
    try {/* ww  w  .  ja v  a  2  s . com*/
        dbCollection.dropIndex(indexName);
    } catch (Throwable t) {
        msg = t.getMessage();
        handleMongoException(t);
    } finally {
        DBObject dropDbo = new BasicDBObject();
        dropDbo.put("indexname", indexName);
        logMongoAction(context, "dropIndex", start, dbCollection, dropDbo, null, null, null, msg);
    }
}

From source file:com.ikanow.infinit.e.processing.generic.GenericProcessingController.java

License:Open Source License

private static void dropIndexIfNotNeeded(DBCollection coll, String indexToCheck, int nIndexToCheckIndex,
        String indexToDelete, int nIndexToDeleteIndex) {
    StringBuffer indexNameStrBuff = new StringBuffer(indexToCheck);
    if (0 != nIndexToCheckIndex) {
        indexNameStrBuff.append("_").append(nIndexToCheckIndex);
    }//from  w ww. j  a v a2  s. c om
    String indexToCheck2 = indexNameStrBuff.toString();
    indexNameStrBuff.setLength(0);
    indexNameStrBuff.append(indexToDelete);
    if (0 != nIndexToDeleteIndex) {
        indexNameStrBuff.append("_").append(nIndexToDeleteIndex);
    }

    boolean foundIndexToDelete = false;
    boolean foundIndexToCheck = false;
    String indexToDelete2 = indexNameStrBuff.toString();
    List<DBObject> list = coll.getIndexInfo();
    for (DBObject dbo : list) {
        String name = (String) dbo.get("name");
        if (indexToCheck2.equalsIgnoreCase(name)) {
            foundIndexToCheck = true;
        } else if (indexToDelete2.equalsIgnoreCase(name)) {
            foundIndexToDelete = true;
        }
    }
    if (foundIndexToCheck && foundIndexToDelete) {
        try {
            coll.dropIndex(indexToDelete2);
        } catch (Exception e) {
        }
    }
}

From source file:com.ikanow.infinit.e.processing.generic.GenericProcessingController.java

License:Open Source License

private void dropIndexIfItExists(DBCollection coll, String indexName, int nIndexIndex) {
    StringBuffer indexNameStrBuff = new StringBuffer(indexName);
    if (0 != nIndexIndex) {
        indexNameStrBuff.append("_").append(nIndexIndex);
    }//from  w ww  . ja va 2s  .c  o m
    String indexName2 = indexNameStrBuff.toString();
    List<DBObject> list = coll.getIndexInfo();
    for (DBObject dbo : list) {
        String name = (String) dbo.get("name");
        if (indexName2.equalsIgnoreCase(name)) {
            try {
                coll.dropIndex(name);
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.liferay.mongodb.hook.listeners.ExpandoColumnListener.java

License:Open Source License

protected void doOnAfterRemove(ExpandoColumn expandoColumn) throws Exception {

    ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(expandoColumn.getTableId());

    DBCollection dbCollection = MongoDBUtil.getCollection(expandoTable);

    for (DBObject indexDBObject : dbCollection.getIndexInfo()) {
        DBObject keyDBObject = (DBObject) indexDBObject.get("key");

        if (keyDBObject.containsField(expandoColumn.getName())) {
            dbCollection.dropIndex(keyDBObject);
        }//w w w. j a va2  s.c  o m
    }

    DBObject operatorDBObject = new BasicDBObject(MongoOperator.UNSET,
            new BasicDBObject(expandoColumn.getName(), 1));

    dbCollection.update(new BasicDBObject(), operatorDBObject, false, true);
}

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  w  w. j  ava  2s .c  o  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);
        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  va 2 s .c  o 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:net.kamradtfamily.mongorest.IndexServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.fine("doDelete()");

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        error(res, SC_BAD_REQUEST, Status.get("param name missing"));
        return;/*from w  w w  .java2s.com*/
    }

    BufferedReader r = null;
    String data = null;

    try {

        r = new BufferedReader(new InputStreamReader(is));
        data = r.readLine();

    } finally {
        if (r != null)
            r.close();
    }
    if (data == null) {
        error(res, SC_BAD_REQUEST, Status.get("no data"));
        return;
    }

    DBObject o;
    try {
        o = (DBObject) JSON.parse(data);
    } catch (JSONParseException e) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    col.dropIndex(o);

    res.setStatus(SC_OK);

}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections/{collName}/indexes/{indexName}")
@Override//  w w  w. ja v  a  2  s . c  o  m
public Response deleteIndex(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @PathParam("indexName") String indexName, @Context HttpHeaders headers, @Context UriInfo uriInfo,
        @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                List<DBObject> indexInfos = dbCollection.getIndexInfo();
                boolean indexFound = false;
                for (DBObject indexInfo : indexInfos) {
                    String foundIndexName = (String) indexInfo.get("name");
                    if (foundIndexName.equals(indexName)) {
                        indexFound = true;
                        dbCollection.dropIndex(indexName);
                        break;
                    }
                }
                if (indexFound) {
                    response = Response.ok().build();
                } else {
                    response = Response.status(ClientError.NOT_FOUND.code())
                            .entity(indexName + " does not exist for " + collName).build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "deleteIndex");
    }

    return response;
}