Example usage for com.mongodb DBCollection dropIndexes

List of usage examples for com.mongodb DBCollection dropIndexes

Introduction

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

Prototype

public void dropIndexes() 

Source Link

Document

Drop all indexes on this collection.

Usage

From source file:br.bireme.scl.BrokenLinks.java

License:Open Source License

public static int createLinks(final String outCheckFile, final String outEncoding, final String mstName,
        final String mstEncoding, final String host, final int port, final String user, final String password,
        final boolean clearCol, final String[] allowedMessages) throws BrumaException, IOException {
    if (outCheckFile == null) {
        throw new NullPointerException("outCheckFile");
    }//ww w  .ja  va  2 s  .  c  o  m
    if (outEncoding == null) {
        throw new NullPointerException("outEncoding");
    }
    if (mstName == null) {
        throw new NullPointerException("mstName");
    }
    if (mstEncoding == null) {
        throw new NullPointerException("mstEncoding");
    }
    if (host == null) {
        throw new NullPointerException("host");
    }
    if (port <= 0) {
        throw new IllegalArgumentException("port <= 0");
    }
    if (allowedMessages == null) {
        throw new NullPointerException("allowedMessages");
    }

    final Master mst = MasterFactory.getInstance(mstName).setEncoding(mstEncoding).open();
    final String mName = new File(mst.getMasterName()).getName();
    final BufferedReader in = new BufferedReader(
            new InputStreamReader(new FileInputStream(outCheckFile), outEncoding));
    final MongoClient mongoClient = new MongoClient(host, port);
    final DB db = mongoClient.getDB(SOCIAL_CHECK_DB);
    // map -> mfn ->  url,occ
    final Map<Integer, Map<String, Integer>> occMap = new HashMap<Integer, Map<String, Integer>>();
    final boolean checkPassword = false;
    if (checkPassword) {
        final boolean auth = db.authenticate(user, password.toCharArray());
        if (!auth) {
            throw new IllegalArgumentException("invalid user/password");
        }
    }

    final DBCollection coll = db.getCollection(BROKEN_LINKS_COL);
    final DBCollection ccColl = db.getCollection(CC_FIELDS_COL);
    final DBCollection hColl = db.getCollection(HISTORY_COL);

    if (ccColl.findOne() == null) {
        if (!createCcFieldsCollection(ccColl)) {
            throw new IOException("CC fields collection creation failed");
        }
    }
    final int idTag = getIsisIdField(mName, ccColl);
    final int urlTag = getIsisUrlFields(mName, ccColl);
    if (urlTag <= 0) {
        throw new IOException("Missing Isis url fields");
    }
    final List<Integer> tags = getIsisCcFields(mName, ccColl);
    final Set<String> allowedMess = new HashSet<String>(Arrays.asList(allowedMessages));
    final Map<String, Integer> idMap = getIdMfn(mst, idTag);
    int tell = 0;
    int tot = 0;

    if (clearCol) {
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    }

    System.out.println("Saving documents ...");
    while (true) {
        final String line = in.readLine();
        if (line == null) {
            break;
        }
        final String lineT = line.trim();
        if (!lineT.isEmpty()) {
            final String[] split = lineT.split(" *\\| *", 4); //id|url|msg|master
            if (split.length < 4) {
                throw new IOException("Wrong line format: " + line);
            }
            final int openPos = split[2].indexOf('('); // cut extra data               
            final String prefix = (openPos > 0) ? split[2].substring(0, openPos) : split[2];

            if (allowedMess.contains(prefix.trim())) {
                final Integer id = idMap.get(split[0]);
                if (id == null) {
                    throw new IOException("id[" + split[0] + "] not found");
                }

                final String url_e = EncDecUrl.encodeUrl(split[1], outEncoding, false);

                saveRecord(mName, id, url_e, split[2], urlTag, tags, mst, coll, hColl, occMap);
                tot++;
            }
            if (++tell % 5000 == 0) {
                System.out.println("++" + tell);
            }
        }
    }

    System.out.print("\nFixing urls that do not start with http:// ... ");
    MongoOperations.fixMissingHttp(coll, hColl);
    System.out.println(" - OK");

    //removeOldDocs(coll);

    if (clearCol) {
        createIndex(coll);
    }

    in.close();
    mst.close();

    return tot;
}

From source file:com.mebigfatguy.mongobrowser.actions.ManageIndicesAction.java

License:Apache License

private void updateIndices(DBCollection collection, List<IndexDescription> indices) {

    collection.dropIndexes();

    for (IndexDescription index : indices) {
        if (!MongoConstants.ID_INDEX.equals(index.getIndexName())) {

            BasicDBObject dbFields = new BasicDBObject();
            IndexFieldList fieldList = index.getIndexFieldList();

            for (IndexField field : fieldList) {
                dbFields.append(field.getFieldName(), Integer.valueOf(field.isAscending() ? 1 : -1));
            }// w w w. j  a  va  2s  .  c o m

            collection.ensureIndex(dbFields, index.getIndexName());
        }
    }
}

From source file:org.apache.camel.component.mongodb.MongoDbEndpoint.java

License:Apache License

/**
 * Add Index/*from ww  w . j a  v a 2s. c o m*/
 *
 * @param collection
 */
public void ensureIndex(DBCollection collection, List<DBObject> dynamicIndex) {
    collection.dropIndexes();
    if (dynamicIndex != null && !dynamicIndex.isEmpty()) {
        for (DBObject index : dynamicIndex) {
            LOG.debug("create BDObject Index {}", index);
            collection.ensureIndex(index);
        }
    }
}

From source file:org.benjp.services.mongodb.MongoBootstrap.java

License:Open Source License

public void ensureIndexes() {
    String dbName = this.getDB().getName();
    log.info("### ensureIndexes in " + dbName);
    BasicDBObject unique = new BasicDBObject();
    unique.put("unique", true);
    unique.put("background", true);
    BasicDBObject notUnique = new BasicDBObject();
    notUnique.put("unique", false);
    notUnique.put("background", true);

    DBCollection notifications = getDB().getCollection("notifications");
    notifications.dropIndexes();
    notifications.createIndex(new BasicDBObject("user", 1),
            notUnique.append("name", "user_1").append("ns", dbName + ".notifications"));
    notifications.createIndex(new BasicDBObject("isRead", 1),
            notUnique.append("name", "isRead_1").append("ns", dbName + ".notifications"));
    BasicDBObject index = new BasicDBObject();
    index.put("user", 1);
    index.put("categoryId", 1);
    index.put("category", 1);
    index.put("type", 1);
    //    index.put("isRead", 1);
    notifications.createIndex(index, notUnique.append("name", "user_1_type_1_category_1_categoryId_1")
            .append("ns", dbName + ".notifications"));
    log.info("### notifications indexes in " + getDB().getName());

    DBCollection rooms = getDB().getCollection("room_rooms");
    rooms.dropIndexes();//from www  . j  a va 2s .co  m
    rooms.createIndex(new BasicDBObject("space", 1),
            notUnique.append("name", "space_1").append("ns", dbName + ".room_rooms"));
    rooms.createIndex(new BasicDBObject("users", 1),
            notUnique.append("name", "users_1").append("ns", dbName + ".room_rooms"));
    rooms.createIndex(new BasicDBObject("shortName", 1),
            notUnique.append("name", "shortName_1").append("ns", dbName + ".room_rooms"));
    log.info("### rooms indexes in " + getDB().getName());

    DBCollection coll = getDB()
            .getCollection(ChatServiceImpl.M_ROOM_PREFIX + ChatServiceImpl.M_ROOMS_COLLECTION);
    DBCursor cursor = coll.find();
    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();
        String roomId = dbo.get("_id").toString();
        DBCollection collr = getDB().getCollection(ChatServiceImpl.M_ROOM_PREFIX + roomId);
        collr.ensureIndex(new BasicDBObject("timestamp", 1),
                notUnique.append("name", "timestamp_1").append("ns", dbName + ".room_" + roomId));
        collr.ensureIndex(new BasicDBObject("timestamp", -1),
                notUnique.append("name", "timestamp_m1").append("ns", dbName + ".room_" + roomId));
        log.info("##### room index in " + roomId);
    }

    DBCollection users = getDB().getCollection("users");
    users.dropIndexes();
    users.createIndex(new BasicDBObject("token", 1),
            notUnique.append("name", "token_1").append("ns", dbName + ".users"));
    users.createIndex(new BasicDBObject("validity", -1),
            notUnique.append("name", "validity_m1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("user", 1);
    index.put("token", 1);
    users.createIndex(index, unique.append("name", "user_1_token_1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("user", 1);
    index.put("validity", -1);
    users.createIndex(index, unique.append("name", "user_1_validity_m1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("validity", -1);
    index.put("isDemoUser", 1);
    users.createIndex(index,
            notUnique.append("name", "validity_1_isDemoUser_m1").append("ns", dbName + ".users"));

    users.createIndex(new BasicDBObject("user", 1),
            unique.append("name", "user_1").append("ns", dbName + ".users"));
    users.createIndex(new BasicDBObject("spaces", 1),
            notUnique.append("name", "spaces_1").append("ns", dbName + ".users"));
    log.info("### users indexes in " + getDB().getName());

    log.info("### Indexes creation completed in " + getDB().getName());

}

From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java

License:Open Source License

@Override
public void deleteSchemaForClasses(Set<String> classNames, Properties props, Object connection) {
    DB db = (DB) connection;//  w  w  w  .  j  av a  2  s . c  om
    ManagedConnection mconn = null;
    try {
        if (db == null) {
            mconn = storeMgr.getConnection(-1);
            db = (DB) mconn.getConnection();
        }

        Iterator<String> classIter = classNames.iterator();
        ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null);
        while (classIter.hasNext()) {
            String className = classIter.next();
            AbstractClassMetaData cmd = storeMgr.getMetaDataManager().getMetaDataForClass(className, clr);
            if (cmd != null) {
                StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName());
                Table table = null;
                if (storeData != null) {
                    table = storeData.getTable();
                } else {
                    table = new CompleteClassTable(storeMgr, cmd, null);
                }
                DBCollection collection = db.getCollection(table.getName());
                collection.dropIndexes();
                if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
                    NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.SchemaDelete.Class",
                            cmd.getFullClassName(), table.getName()));
                }
                collection.drop();
            }
        }
    } finally {
        if (mconn != null) {
            mconn.release();
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBStoreManager.java

License:Open Source License

public void deleteSchema(Set<String> classNames, Properties props) {
    ManagedConnection mconn = getConnection(-1);
    try {// w w  w.j  av  a 2 s  .  c o  m
        DB db = (DB) mconn.getConnection();

        Iterator<String> classIter = classNames.iterator();
        ClassLoaderResolver clr = nucleusContext.getClassLoaderResolver(null);
        while (classIter.hasNext()) {
            String className = classIter.next();
            AbstractClassMetaData cmd = getMetaDataManager().getMetaDataForClass(className, clr);
            if (cmd != null) {
                DBCollection collection = db.getCollection(getNamingFactory().getTableName(cmd));
                collection.dropIndexes();
                collection.drop();
            }
        }
    } finally {
        mconn.release();
    }
}

From source file:org.exoplatform.chat.services.mongodb.MongoBootstrap.java

License:Open Source License

public void ensureIndexes() {
    String dbName = this.getDB().getName();
    LOG.info("### ensureIndexes in " + dbName);
    BasicDBObject unique = new BasicDBObject();
    unique.put("unique", true);
    unique.put("background", true);
    BasicDBObject notUnique = new BasicDBObject();
    notUnique.put("unique", false);
    notUnique.put("background", true);

    DBCollection notifications = getDB().getCollection("notifications");
    notifications.dropIndexes();
    notifications.createIndex(new BasicDBObject("user", 1),
            notUnique.append("name", "user_1").append("ns", dbName + ".notifications"));
    notifications.createIndex(new BasicDBObject("isRead", 1),
            notUnique.append("name", "isRead_1").append("ns", dbName + ".notifications"));
    BasicDBObject index = new BasicDBObject();
    index.put("user", 1);
    index.put("categoryId", 1);
    index.put("category", 1);
    index.put("type", 1);
    //    index.put("isRead", 1);
    notifications.createIndex(index, notUnique.append("name", "user_1_type_1_category_1_categoryId_1")
            .append("ns", dbName + ".notifications"));
    LOG.info("### notifications indexes in " + getDB().getName());

    DBCollection rooms = getDB().getCollection("room_rooms");
    rooms.dropIndexes();/*  w w w . jav a2 s  .  co  m*/
    rooms.createIndex(new BasicDBObject("space", 1),
            notUnique.append("name", "space_1").append("ns", dbName + ".room_rooms"));
    rooms.createIndex(new BasicDBObject("users", 1),
            notUnique.append("name", "users_1").append("ns", dbName + ".room_rooms"));
    rooms.createIndex(new BasicDBObject("shortName", 1),
            notUnique.append("name", "shortName_1").append("ns", dbName + ".room_rooms"));
    LOG.info("### rooms indexes in " + getDB().getName());

    DBCollection coll = getDB()
            .getCollection(ChatServiceImpl.M_ROOM_PREFIX + ChatServiceImpl.M_ROOMS_COLLECTION);
    DBCursor cursor = coll.find();
    while (cursor.hasNext()) {
        DBObject dbo = cursor.next();
        String roomId = dbo.get("_id").toString();
        DBCollection collr = getDB().getCollection(ChatServiceImpl.M_ROOM_PREFIX + roomId);
        collr.ensureIndex(new BasicDBObject("timestamp", 1),
                notUnique.append("name", "timestamp_1").append("ns", dbName + ".room_" + roomId));
        collr.ensureIndex(new BasicDBObject("timestamp", -1),
                notUnique.append("name", "timestamp_m1").append("ns", dbName + ".room_" + roomId));
        LOG.info("##### room index in " + roomId);
    }

    DBCollection users = getDB().getCollection("users");
    users.dropIndexes();
    users.createIndex(new BasicDBObject("token", 1),
            notUnique.append("name", "token_1").append("ns", dbName + ".users"));
    users.createIndex(new BasicDBObject("validity", -1),
            notUnique.append("name", "validity_m1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("user", 1);
    index.put("token", 1);
    users.createIndex(index, unique.append("name", "user_1_token_1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("user", 1);
    index.put("validity", -1);
    users.createIndex(index, unique.append("name", "user_1_validity_m1").append("ns", dbName + ".users"));
    index = new BasicDBObject();
    index.put("validity", -1);
    index.put("isDemoUser", 1);
    users.createIndex(index,
            notUnique.append("name", "validity_1_isDemoUser_m1").append("ns", dbName + ".users"));

    users.createIndex(new BasicDBObject("user", 1),
            unique.append("name", "user_1").append("ns", dbName + ".users"));
    users.createIndex(new BasicDBObject("spaces", 1),
            notUnique.append("name", "spaces_1").append("ns", dbName + ".users"));
    LOG.info("### users indexes in " + getDB().getName());

    LOG.info("### Indexes creation completed in " + getDB().getName());

}

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

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections/{collName}")
@Override/*w ww .j  a v  a2  s  . c  o m*/
public Response deleteCollection(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @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 collection = db.getCollection(collName);
                collection.dropIndexes();
                collection.drop();
                response = Response.ok().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, "deleteCollection");
    }

    return response;
}

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

License:Open Source License

@DELETE
@Path("/databases/{dbName}/collections")
@Override//ww w.  ja  va 2  s.  com
public Response deleteCollections(@PathParam("dbName") String dbName, @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);
            List<String> collections = new ArrayList<String>();
            for (String collName : db.getCollectionNames()) {
                if (collName.equals(SYS_INDEXES_COLLECTION)) {
                    continue;
                }
                collections.add(collName);
                DBCollection collection = db.getCollection(collName);
                collection.dropIndexes();
                collection.drop();
            }
            response = Response.ok("Deleted collections: " + collections).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, "deleteCollections");
    }

    return response;
}

From source file:org.nuxeo.ecm.core.storage.mongodb.MongoDBRepositoryTestCase.java

License:Open Source License

protected void clearMongoDb() throws UnknownHostException {
    MongoClient mongoClient = MongoDBRepository.newMongoClient(descriptor);
    try {//from w  w  w.  j a v  a 2  s  .  c om
        DBCollection coll = MongoDBRepository.getCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
        coll = MongoDBRepository.getCountersCollection(descriptor, mongoClient);
        coll.dropIndexes();
        coll.remove(new BasicDBObject());
    } finally {
        mongoClient.close();
    }
}