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) 

Source Link

Document

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

Usage

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

License:GNU General Public License

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

    log.fine("doPut()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);//from  www.  j  a va2 s  .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;
    }

    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);

    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;
    }

    col.createIndex(o);

    res.setStatus(SC_CREATED);

}

From source file:com.cubeia.poker.handhistory.storage.DatabaseStorageService.java

License:Open Source License

private void initHandsCollection() {
    mongoStorage.map(HistoricHand.class);
    //Indexing/*from   w  ww .  j  ava  2s.  c o  m*/
    DBCollection coll = mongoStorage.getCollection(HistoricHand.class.getSimpleName());
    if (0 == coll.getCount()) {
        coll.createIndex(new BasicDBObject("startTime", -1));
    }
}

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

License:GNU General Public License

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

    log.trace("doPut()");

    if (!can_admin(req)) {
        res.sendError(SC_UNAUTHORIZED);// w ww  .  j a v a 2s . c om
        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;
    }

    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);

    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;
    }

    col.createIndex(o);

    res.setStatus(SC_CREATED);

}

From source file:com.datumbox.common.persistentstorage.factories.MongoDBStructureFactory.java

License:Open Source License

private <K, V> Map<K, V> getMongoConcurrentMap(String collectionName) {
    DBCollection collection = db.getCollection(collectionName);
    // the serializers for mapping DBObjects to String and vice versa
    DBObjectSerializer<K> keySerializer = new SimpleFieldDBObjectSerializer<>("k");
    DBObjectSerializer<V> valueSerializer = new SimpleFieldDBObjectSerializer<>("v");
    // will produce documents like "{'k':...,'v':...,'_id':ObjectID(...)}"
    Map<K, V> mongoMap = new MongoConcurrentMap<>(collection, keySerializer, valueSerializer);

    //collection.createIndex(new BasicDBObject("k", 1)); //create an index on k
    if (StorageConfiguration.MongoDB.USE_HASH_INDEXES_IN_MAPS) {
        collection.createIndex(new BasicDBObject("k", "hashed")); //hash index
    } else {/* w ww  .java2 s  . c  om*/
        //uniques are not supported for lists
        //collection.createIndex(new BasicDBObject("k", 1), new BasicDBObject("unique", true)); //unique btree index
        collection.createIndex(new BasicDBObject("k", 1));
    }

    return mongoMap;
}

From source file:com.ikanow.infinit.e.data_model.store.MongoDbManager.java

License:Apache License

@SuppressWarnings("deprecation")
public static void main(String[] args) throws UnknownHostException {
    MongoClient mc = new MongoClient(args[0]);
    long tnow = 0;
    DB db = mc.getDB("test");
    DBCollection test = db.getCollection("test123");
    BasicDBObject outObj = new BasicDBObject();
    int ITS = 1000;
    test.drop();/*from  www  .  j  ava  2s.  co m*/

    boolean checkPerformance = false;
    boolean checkFunctionality = false;
    boolean checkErrors = false;

    // 1] Performance

    if (checkPerformance) {

        // ack'd
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("1: Ack'd: " + tnow);

        // un ack'd
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("2: unAck'd: " + tnow);

        // un ack'd but call getLastError
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        test.drop();
        System.out.println("3: unAck'd but GLEd: " + tnow);

        // ack'd override
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        test.drop();
        tnow = new Date().getTime();
        outObj = new BasicDBObject();
        for (int i = 0; i < ITS; ++i) {
            outObj.remove("_id");
            outObj.put("val", i);
            test.save(outObj, WriteConcern.ACKNOWLEDGED);
            db.getLastError();
        }
        tnow = new Date().getTime() - tnow;
        System.out.println("4: unAck'd but ACKd: " + tnow);

        // Performance Results:
        // 2.6) (unack'd 100ms ... ack'd 27000)
        // 2.4) (same)
    }

    // 2] Functionality

    if (checkFunctionality) {

        // Unack:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        WriteResult wr = test.update(new BasicDBObject(),
                new BasicDBObject(DbManager.set_, new BasicDBObject("val2", "x")), false, true);
        CommandResult cr = db.getLastError();
        System.out.println("UNACK: wr: " + wr);
        System.out.println("UNACK: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        WriteResult wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);
        CommandResult cr2 = db.getLastError();
        System.out.println("ACK cr2 = " + cr2);

        // Ack1:
        db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val3", "x")),
                false, true);
        cr = db.getLastError();
        System.out.println("ACK1: wr: " + wr);
        System.out.println("ACK1: cr: " + cr);

        // Ack2:
        db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
        wr = test.update(new BasicDBObject(), new BasicDBObject(DbManager.set_, new BasicDBObject("val4", "x")),
                false, true, WriteConcern.ACKNOWLEDGED);
        cr = db.getLastError();
        System.out.println("ACK2: wr: " + wr);
        System.out.println("ACK2: cr: " + cr);

        // bonus, check that we get N==0 when insert dup object
        wr2 = test.insert(outObj);
        System.out.println("ACK wr2 = " + wr2.getN() + " all = " + wr2);

        // Functionality results:
        // 2.6: unack wr == N/A, otherwise both have "n", "ok"
        // 2.4: unack wr == N/A all other wrs + crs identical 
    }

    if (checkErrors) {

        //set up sharding
        DbManager.getDB("admin").command(new BasicDBObject("enablesharding", "test"));
        // Ack:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.ACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("ACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")), false, false,
                    WriteConcern.ACKNOWLEDGED);
            System.out.println("ACK override wr = " + wr);
        } catch (Exception e) {
            System.out.println("ACK override  err = " + e.toString());
        }

        // UnAck:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            System.out.println("UNACK wr = " + wr);
        } catch (Exception e) {
            System.out.println("UNACK err = " + e.toString());
        }

        // UnAck + GLE:
        try {
            test.drop();
            test.createIndex(new BasicDBObject("key", 1));
            BasicDBObject command1 = new BasicDBObject("shardcollection", "test.test123");
            command1.append("key", new BasicDBObject("key", 1));
            DbManager.getDB("admin").command(command1);

            db.setWriteConcern(WriteConcern.UNACKNOWLEDGED);
            outObj = new BasicDBObject("key", "test");
            test.save(outObj);
            WriteResult wr = test.update(new BasicDBObject(),
                    new BasicDBObject(DbManager.set_, new BasicDBObject("key", "test2")));
            CommandResult cr = db.getLastError();
            System.out.println("UNACK GLE wr = " + wr);
            System.out.println("UNACK GLE cr = " + cr);
        } catch (Exception e) {
            System.out.println("UNACK GLE err = " + e.toString());
        }

        // Error handling:

        // 2.6:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

        // 2.4:
        // Ack - exception
        // Ack override - exception
        // UnAck - no error given
        // UnAck + GLE  - gle error

    }
}

From source file:com.images3.data.impl.MongoDBAccessProvider.java

License:Apache License

private void initPageCursor(DB db) {
    DBCollection coll = db.getCollection("PageCursor");
    coll.createIndex(new BasicDBObject("id", "hashed"));
    coll.createIndex(new BasicDBObject("creationTime", 1));
}

From source file:com.images3.data.impl.MongoDBAccessProvider.java

License:Apache License

private void initImagePlant(DB db) {
    DBCollection coll = db.getCollection("ImagePlant");
    coll.createIndex(new BasicDBObject("id", "hashed"));
    coll.createIndex(new BasicDBObject("nameKey", 1), new BasicDBObject("unique", true));
    coll.createIndex(new BasicDBObject("creationTime", 1));
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Creates the index.//from   ww  w  .  j  a  v  a 2s .c  o m
 * 
 * @param collectionName
 *            the collection name
 * @param columnList
 *            the column list
 * @param order
 *            the order
 */
public void createIndex(String collectionName, List<String> columnList, int order) {
    DBCollection coll = mongoDb.getCollection(collectionName);

    List<DBObject> indexes = coll.getIndexInfo(); // List of all current
    // indexes on collection
    Set<String> indexNames = new HashSet<String>(); // List of all current
    // index names
    for (DBObject index : indexes) {
        BasicDBObject obj = (BasicDBObject) index.get("key");
        Set<String> set = obj.keySet(); // Set containing index name which
        // is key
        indexNames.addAll(set);
    }

    // Create index if not already created
    for (String columnName : columnList) {
        if (!indexNames.contains(columnName)) {
            KunderaCoreUtils.printQuery("Create index on:" + columnName, showQuery);
            coll.createIndex(new BasicDBObject(columnName, order));
        }
    }
}

From source file:com.intuit.utils.PopulateTweets.java

public static void main(String[] args) {
    Date now = new Date();
    System.out.println("Current date is: " + now.toString());

    MongoClient mongo = new MongoClient("localhost", 27017);
    DB db = mongo.getDB("tweetsdb");
    DBCollection collection = db.getCollection("tweetscollection");
    WriteResult result = collection.remove(new BasicDBObject());

    String[] users = { "user1", "user2", "user3", "user4", "user5", "user6", "user7", "user8", "user9",
            "user10" };
    // I am not introducing enough randomness in terms of the insertion of 
    // tweets for users at a random time orders, due to lack of time.
    for (String user : users) {
        int tweetIndex = 0;
        for (int i = 1; i <= 10; i++) {
            BasicDBObject document = new BasicDBObject();
            // This is a way to maintain uniqueness of the tweetid value across the system
            // Ideally, this should be the "_id" value, but due to lack of time, I am skipping
            // that part.  That would help to partition the tweets across multiple shards in a 
            // large scale system.
            String tweetId = user + "|tweet" + tweetIndex;
            document.put("tweetId", tweetId);
            document.put("user", user);
            document.put("text", "tweet number" + tweetIndex);
            document.put("tweetedOn", new Date().toString());
            System.out.println("tweet number: " + tweetIndex + "   " + document.toString());
            collection.insert(document);
            tweetIndex++;/*from  w  w w.j ava 2s. c  o m*/
            try {
                // Just introducing some delay between tweets to make the testing a bit easy
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(PopulateTweets.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    BasicDBObject indexObj = new BasicDBObject();
    indexObj.put("user", 1);
    indexObj.put("tweetedOn", -1);
    collection.createIndex(indexObj);

    BasicDBObject tweetIdObj = new BasicDBObject();
    tweetIdObj.put("tweetId", 1);
    collection.createIndex(tweetIdObj);
}

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

License:Open Source License

@Override
public void onAfterCreate(ExpandoTable expandoTable) {
    DB db = MongoDBUtil.getDB(expandoTable.getCompanyId());

    String collectionName = MongoDBUtil.getCollectionName(expandoTable.getClassName(), expandoTable.getName());

    if (!db.collectionExists(collectionName)) {
        DBCollection dbCollection = db.createCollection(collectionName, null);

        dbCollection.createIndex(new BasicDBObject("valueId", 1));
        dbCollection.createIndex(new BasicDBObject("companyId", 1));
        dbCollection.createIndex(new BasicDBObject("tableId", 1));
        dbCollection.createIndex(new BasicDBObject("rowId", 1));
        dbCollection.createIndex(new BasicDBObject("classNameId", 1));
        dbCollection.createIndex(new BasicDBObject("classPK", 1));
    }//from   ww w . j  a v  a  2s .  c o m
}