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.liferay.mongodb.hook.service.impl.MongoExpandoColumnLocalServiceImpl.java

License:Open Source License

@Override
public ExpandoColumn updateTypeSettings(long columnId, String typeSettings) throws PortalException {

    ExpandoColumn expandoColumn = super.updateTypeSettings(columnId, typeSettings);

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

    UnicodeProperties typeSettingsProperties = expandoColumn.getTypeSettingsProperties();

    int indexType = GetterUtil
            .getInteger(typeSettingsProperties.getProperty(ExpandoColumnConstants.INDEX_TYPE));

    if (indexType != ExpandoColumnConstants.INDEX_TYPE_NONE) {
        DBCollection dbCollection = MongoDBUtil.getCollection(expandoTable);

        dbCollection.createIndex(new BasicDBObject(expandoColumn.getName(), 1));
    }/*from w w  w.  j  a  va  2s .  co  m*/

    return expandoColumn;
}

From source file:edu.sjsu.carbonated.client.MongoDBDOA.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server
    Mongo m = new Mongo();

    // get handle to "mydb"
    DB db = m.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get a list of the collections in this database and print them out
    Set<String> colls = db.getCollectionNames();
    for (String s : colls) {
        System.out.println(s);/*w ww . j  av  a 2  s .com*/
    }

    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject();

    doc.put("test", new AlbumResource("name", "desc", "user", "asdf"));
    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        coll.insert(new BasicDBObject().append("i", i));
    }
    System.out
            .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());

    //  lets get all the documents in the collection and print them out
    DBCursor cur = coll.find();
    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject();
    query.put("i", 71);
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a range query to get a larger subset
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // range query with multiple contstraings
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

    //  list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (DBObject o : list) {
        System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();
}

From source file:es.devcircus.mongodb_examples.hello_world.Main.java

License:Open Source License

/**
 * Mtodo que crea un ndice.//  ww w  .java2s .c om
 */
public static void creatingAnIndex() {

    System.out.println();
    System.out.println("---------------------------------------------------------------");
    System.out.println(" Creating An Index                                             ");
    System.out.println("---------------------------------------------------------------");
    System.out.println();

    /*Creating An Index
     MongoDB supports indexes, and they are very easy to add on a collection. 
     * To create an index, you just specify the field that should be indexed, 
     * and specify if you want the index to be ascending (1) or descending 
     * (-1). The following creates an ascending index on the "i" field :*/

    DBCollection coll = db.getCollection(TEST_COLLECTION);

    System.out.print(" Creando ndice ...");
    // create index on "i", ascending
    coll.createIndex(new BasicDBObject("i", 1));
    System.out.println("[OK]");

}

From source file:example.QuickTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args/*from  ww  w.j  a  v a  2s .  co  m*/
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get a list of the collections in this database and print them out
    Set<String> collectionNames = db.getCollectionNames();
    for (final String s : collectionNames) {
        System.out.println(s);
    }

    // get a collection object to work with
    DBCollection testCollection = db.getCollection("testCollection");

    // drop all the data in it
    testCollection.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
            .append("info", new BasicDBObject("x", 203).append("y", 102));

    testCollection.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = testCollection.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        testCollection.insert(new BasicDBObject().append("i", i));
    }
    System.out.println(
            "total # of documents after inserting 100 small ones (should be 101) " + testCollection.getCount());

    // lets get all the documents in the collection and print them out
    DBCursor cursor = testCollection.find();
    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject("i", 71);
    cursor = testCollection.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // now use a range query to get a larger subset
    query = new BasicDBObject("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cursor = testCollection.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // range query with multiple constraints
    query = new BasicDBObject("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
    cursor = testCollection.find(query);

    try {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } finally {
        cursor.close();
    }

    // create an index on the "i" field
    testCollection.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

    // list the indexes on the collection
    List<DBObject> list = testCollection.getIndexInfo();
    for (final DBObject o : list) {
        System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();

    // release resources
    mongoClient.close();
}

From source file:examples.QuickTour.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server
    Mongo m = new Mongo();

    // get handle to "mydb"
    DB db = m.getDB("mydb");

    // Authenticate - optional
    boolean auth = db.authenticate("foo", new char[] { 'b', 'a', 'r' });

    // get a list of the collections in this database and print them out
    Set<String> colls = db.getCollectionNames();
    for (String s : colls) {
        System.out.println(s);/*from w  w w .  j  a  v a2s.  c  om*/
    }

    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject();

    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        coll.insert(new BasicDBObject().append("i", i));
    }
    System.out
            .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());

    //  lets get all the documents in the collection and print them out
    DBCursor cur = coll.find();
    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject();
    query.put("i", 71);
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a range query to get a larger subset
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // range query with multiple contstraings
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

    //  list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (DBObject o : list) {
        System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();
}

From source file:fr.cirad.web.controller.gigwa.base.AbstractVariantController.java

License:Open Source License

/**
 * List variants./*w  ww.j a va 2 s.  c  o m*/
 *
 * @param request the request
 * @param sModule the module
 * @param projId the proj id
 * @param selectedVariantTypes the selected variant types
 * @param selectedSequences the selected sequences
 * @param selectedIndividuals the selected individuals
 * @param gtPattern the gt code
 * @param genotypeQualityThreshold the genotype quality threshold
 * @param readDepthThreshold the read depth threshold
 * @param missingData the missing data
 * @param minmaf the minmaf
 * @param maxmaf the maxmaf
 * @param minposition the minposition
 * @param maxposition the maxposition
 * @param alleleCount the allele count
 * @param geneName the gene name
 * @param variantEffects the variant effects
 * @param wantedFields the wanted fields
 * @param page the page
 * @param size the size
 * @param sortBy the sort by
 * @param sortDir the sort dir
 * @param processID the process id
 * @return the array list
 * @throws Exception the exception
 */
@RequestMapping(variantListURL)
/**
 *  This method returns a list of variants from the current selection
 */
protected @ResponseBody ArrayList<Comparable[]> listVariants(HttpServletRequest request,
        @RequestParam("module") String sModule, @RequestParam("project") int projId,
        @RequestParam("variantTypes") String selectedVariantTypes,
        @RequestParam("sequences") String selectedSequences,
        @RequestParam("individuals") String selectedIndividuals, @RequestParam("gtPattern") String gtPattern,
        @RequestParam("genotypeQualityThreshold") int genotypeQualityThreshold,
        @RequestParam("readDepthThreshold") int readDepthThreshold,
        @RequestParam("missingData") double missingData, @RequestParam("minmaf") Float minmaf,
        @RequestParam("maxmaf") Float maxmaf, @RequestParam("minposition") Long minposition,
        @RequestParam("maxposition") Long maxposition, @RequestParam("alleleCount") String alleleCount,
        @RequestParam("geneName") String geneName, @RequestParam("variantEffects") String variantEffects,
        @RequestParam("wantedFields") String wantedFields, @RequestParam("page") int page,
        @RequestParam("size") int size, @RequestParam("sortBy") String sortBy,
        @RequestParam("sortDir") String sortDir, @RequestParam("processID") String processID) throws Exception {
    String[] usedFields = wantedFields.split(";");

    String token = processID.substring(1 + processID.indexOf('|'));
    String queryKey = getQueryKey(request, sModule, projId, selectedVariantTypes, selectedSequences,
            selectedIndividuals, gtPattern, genotypeQualityThreshold, readDepthThreshold, missingData, minmaf,
            maxmaf, minposition, maxposition, alleleCount, geneName, variantEffects);
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    DBCollection cachedCountcollection = mongoTemplate.getCollection(MgdbDao.COLLECTION_NAME_CACHED_COUNTS);
    //      cachedCountcollection.drop();
    DBCursor countCursor = cachedCountcollection.find(new BasicDBObject("_id", queryKey));
    Object[] partialCountArray = !countCursor.hasNext() ? null
            : ((BasicDBList) countCursor.next().get(MgdbDao.FIELD_NAME_CACHED_COUNT_VALUE)).toArray();

    HashMap<Integer, String> variantFieldMap = new HashMap<Integer, String>(),
            runDataFieldMap = new HashMap<Integer, String>();
    for (int i = 0; i < usedFields.length; i++)
        if (usedFields[i].startsWith("#"))
            variantFieldMap.put(i, usedFields[i].substring(1));
        else
            runDataFieldMap.put(i, usedFields[i]);

    long expectedCount = 0;
    for (Object aPartialCount : partialCountArray)
        expectedCount += (Long) aPartialCount;
    DBCollection tmpVarCollOrView = getTemporaryVariantCollection(sModule, token, false);
    boolean fGotTempData = tmpVarCollOrView.findOne() != null;

    ArrayList<Comparable[]> result = new ArrayList<Comparable[]>();
    DBCollection variantColl = mongoTemplate.getCollection(mongoTemplate.getCollectionName(VariantData.class));
    if (fGotTempData || expectedCount == variantColl.count()) // otherwise we return an empty list because there seems to be a problem (missing temp records)
    {
        boolean fProjectHasAnnotations = getProjectEffectAnnotations(sModule, projId).size() > 0;

        DBCollection varCollForBuildingRows = fGotTempData ? tmpVarCollOrView : variantColl;
        DBCursor variantsInFilterCursor = varCollForBuildingRows.find();

        ArrayList<Object[]> variantRows = buildVariantRows(mongoTemplate, variantsInFilterCursor, sortBy,
                sortDir, page, size, variantFieldMap, runDataFieldMap);
        for (Object[] aRow : variantRows) {
            List<Comparable> anOutputRow = new ArrayList<Comparable>();
            for (int i = 0; i < aRow.length; i++) {
                String val = null;
                if (!usedFields[i].startsWith(VariantRunData.SECTION_ADDITIONAL_INFO + "."))
                    val = aRow[i] == null ? "" : aRow[i].toString();
                else if (aRow[i] != null && fProjectHasAnnotations)
                    val = aRow[i].toString().replaceAll("[\\[\\]\"]", ""); // it's an annotation field: make its content look cleaner
                if (val != null)
                    anOutputRow.add(val);
            }
            anOutputRow.add(anOutputRow.get(0)); // for details link
            result.add(anOutputRow.toArray(new Comparable[anOutputRow.size()]));
        }
    }

    if (fGotTempData && page == 0 && tmpVarCollOrView.getIndexInfo().size() <= 1)
        new Thread() { // temp data needs to be indexed for faster browsing
            public void run() {
                long b4 = System.currentTimeMillis();
                tmpVarCollOrView.createIndex(VariantData.FIELDNAME_VERSION);
                tmpVarCollOrView.createIndex(
                        VariantData.FIELDNAME_REFERENCE_POSITION + "." + ReferencePosition.FIELDNAME_SEQUENCE);
                tmpVarCollOrView.createIndex(VariantData.FIELDNAME_REFERENCE_POSITION + "."
                        + ReferencePosition.FIELDNAME_START_SITE);
                tmpVarCollOrView.createIndex(VariantData.FIELDNAME_TYPE);
                LOG.debug("Indexing " + tmpVarCollOrView.count() + " temp variants took "
                        + (System.currentTimeMillis() - b4) / 1000f + "s");
            }
        }.start();
    return result;
}

From source file:laboratorio_2_sd.Laboratorio_2_SD.java

public static void main(String[] args) throws Exception {

    //archivo de configuracion
    File archivo = new File("config.ini");
    FileReader fr = new FileReader(archivo);
    BufferedReader br = new BufferedReader(fr);
    String linea = br.readLine();
    int cantParticiones = Integer.parseInt(linea);
    linea = br.readLine();/*w w  w  .jav  a 2 s. c o  m*/
    String[] data = linea.split("\n");
    String rutaDocumentos = data[0];
    linea = br.readLine();
    data = linea.split("\n");
    String rutaStopwords = data[0];
    if (imprime)
        System.out.println("Se configura con:\n- Particiones: " + cantParticiones + "\n- Ruta Documentos: '"
                + rutaDocumentos + "'\n- Ruta StopWords: '" + rutaStopwords + "'\n");

    //Archivo stopwords
    File archivo3 = new File(rutaStopwords);
    FileReader fr3 = new FileReader(archivo3);
    BufferedReader br3 = new BufferedReader(fr3);
    ArrayList<String> stopwords = new ArrayList<>();
    if (imprime) {
        System.out.println("StopWords: \n");
        int contador = 0;
        while ((linea = br3.readLine()) != null && linea.length() != 0) {//mientras no sea EOF
            stopwords.add(linea);
            if (contador < 9) {
                System.out.print(linea + " ");
                contador++;
            } else if (contador == 9) {
                contador = 0;
                System.out.println(linea);
            }
        }
        System.out.println("");
    }
    //Crea db y tablas
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    mongoClient.dropDatabase("indexDB");
    DB db = mongoClient.getDB("indexDB");
    mongoClient.setWriteConcern(WriteConcern.JOURNALED);
    db.setWriteConcern(WriteConcern.JOURNALED);

    DBCollection colDocumentos = db.getCollection("Documentos");
    DBCollection colIndiceInvertido = db.getCollection("IndiceInvertido");
    DBCollection colVocabulario = db.getCollection("Vocabulario");

    colDocumentos.createIndex(new BasicDBObject("idDoc", 1));
    colIndiceInvertido.createIndex(new BasicDBObject("idPalabra", 1));
    colVocabulario.createIndex(new BasicDBObject("palabra", 1));

    //Archivo de documentos
    File archivo2 = new File(rutaDocumentos);
    FileReader fr2 = new FileReader(archivo2);
    BufferedReader br2 = new BufferedReader(fr2);

    int idDoc = 0;
    int idPalabraActual = 0;

    while ((linea = br2.readLine()) != null && !linea.contains("</mediawiki>")) {//mientras no sea EOF

        while (!linea.contains("<page>")) {
            linea = br2.readLine();
        }
        //guarda el titulo
        linea = br2.readLine();
        int indice = linea.indexOf(">");
        String sub = linea.substring(indice + 1);
        indice = sub.indexOf("<");
        String titulo = sub.substring(0, indice);

        //guarda el username
        while (!linea.contains("<username>")) {
            linea = br2.readLine();
        }
        indice = linea.indexOf(">");
        sub = linea.substring(indice + 1);
        indice = sub.indexOf("<");
        String username = sub.substring(0, indice);

        while (linea.contains("<text") == false) {
            linea = br2.readLine();
        }

        //Aqui comienza a leer el contenido del documento
        ArrayList<String> palabrasTemp = new ArrayList<String>();

        while (linea.contains("</text>") == false) {

            linea = br2.readLine();

            if (!linea.contains("</text>")) {
                StringTokenizer st = new StringTokenizer(linea, " #%_-*.,;:|/\\(){}[]=&+'\"?!");
                while (st.hasMoreTokens()) {
                    String palabra = st.nextToken();
                    palabra = palabra.toLowerCase();
                    if (palabra.length() > 1 && !stopwords.contains(palabra)) {
                        palabrasTemp.add(palabra);
                    }
                }
            }

        }
        Documento docTemp = new Documento(idDoc, palabrasTemp, titulo, username);
        if (imprime)
            docTemp.print();
        //Se agrega el documento directamente a la coleccion documentos
        colDocumentos.insert(docTemp.toDBObject());

        for (int i = 0; i < docTemp.cantPalabras; i++) {

            String palabra = docTemp.palabras.get(i);
            if (imprime)
                System.out.println("***********************");
            if (imprime)
                System.out.println("Palabra: " + palabra);
            //revisa si la palabra esta en la coleccion vocabulario
            DBCursor cursor = colVocabulario.find((DBObject) new BasicDBObject("palabra", palabra));
            if (cursor.hasNext()) { //si esta
                if (imprime)
                    System.out.println("Esta en vocabulario");
                Vocabulario vocTemp = new Vocabulario((BasicDBObject) cursor.next());
                if (imprime)
                    System.out.println("idPalabra: " + vocTemp.idPalabra);
                DBCursor cursor2 = colIndiceInvertido
                        .find((DBObject) new BasicDBObject("idPalabra", vocTemp.idPalabra));
                BasicDBObject find = (BasicDBObject) cursor2.next();
                IndiceInvertido indiceTemp = new IndiceInvertido(find);
                //revisa si ya est ingresado el documento actual en el indiceInvertido
                int contador = 0;
                int frec = 0;
                for (int j = 0; j < indiceTemp.frecuencias.size(); j++) {
                    if (indiceTemp.frecuencias.get(j).idDocumento == idDoc) {
                        contador = 1;
                        frec = indiceTemp.frecuencias.get(j).frecuencia;
                        break;
                    }
                }
                if (contador == 1) { //si encontro el id del documento actual
                    if (imprime)
                        System.out.println("Esta en indice invertido");
                    //actualizar frecuencia en indice Invertido
                    indiceTemp.ActualizarFrecuencias(frec + 1, idDoc);
                    colIndiceInvertido.update(find, indiceTemp.toDBObject(), false, true);
                    if (imprime)
                        indiceTemp.print();
                } else {//si no est
                    if (imprime)
                        System.out.println("No est en indice invertido");
                    //actualizar la cantidad de documentos del vocabulario
                    vocTemp.cantDocumentos++;
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //agregar nueva tupla de frecuencia/idDoc a indice
                    indiceTemp.ActualizarFrecuencias(1, idDoc);
                    if (imprime)
                        indiceTemp.print();
                    colIndiceInvertido.insert(indiceTemp.toDBObject());

                }
            } else {//no esta
                if (imprime)
                    System.out.println("No esta en vocabulario\nInserta nuevo elemento");
                if (idDoc == 0 && i == 0) { //no se ha insertado ningun dato
                    //inserta palabra en vocabulario
                    Vocabulario vocTemp = new Vocabulario(palabra, 0, 1);
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //inserta entrada en indice invertido
                    IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc);
                    colIndiceInvertido.insert(indiceTemp.toDBObject());
                    if (imprime)
                        indiceTemp.print();
                    idPalabraActual++;
                } else {
                    //se obtiene un nuevo id
                    //se inserta a vocabulario
                    Vocabulario vocTemp = new Vocabulario(palabra, idPalabraActual, 1);
                    colVocabulario.insert(vocTemp.toDBObject());
                    if (imprime)
                        vocTemp.print();
                    //se inserta a indice invertido
                    IndiceInvertido indiceTemp = new IndiceInvertido(vocTemp.idPalabra, 1, idDoc);
                    if (imprime)
                        indiceTemp.print();
                    colIndiceInvertido.insert(indiceTemp.toDBObject());
                    idPalabraActual++;
                }
            }
        }

        idDoc++;
        while (!linea.contains("</page>")) {
            linea = br2.readLine();
        }
        pasarGarbageCollector();
    }

}

From source file:mongoDB.MongoDbClientAllImagesAsByteArrays.java

License:Open Source License

@Override
public void createSchema(Properties props) {

    // drop all collections
    com.mongodb.DB db = null;/*from w w w.j  a va 2  s  .  c om*/
    try {
        // drop database and collections
        // db = mongo.getDB(database);
        db = mongo.getDB("admin");
        db.requestStart();
        // add shards
        /*
         * BasicDBObject addShard = new BasicDBObject("addshard",
         * "10.0.0.138:27011"); CommandResult shardAddResult =
         * db.command(addShard); shardAddResult.getException();
         * System.out.println(shardAddResult.toString()); addShard = new
         * BasicDBObject("addshard", "10.0.0.138:27012"); shardAddResult =
         * db.command(addShard);
         * System.out.println(shardAddResult.toString()); //db.command(
         * " { addshard : \"10.0.0.138:27011\" , allowLocal : true } )");
         */

        db = mongo.getDB(database);
        DBCollection collection = db.getCollection("users");
        collection.drop();
        collection = db.getCollection("resources");
        collection.drop();
        collection = db.getCollection("manipulation");
        collection.drop();

        if (Boolean.parseBoolean(
                props.getProperty(MONGODB_SHARDING_PROPERTY, MONGODB_SHARDING_PROPERTY_DEFAULT)) == true) {
            // enable sharding on the database in the admin user
            db = mongo.getDB("admin");
            BasicDBObject s = new BasicDBObject("enablesharding",
                    props.getProperty(MONGODB_DB_PROPERTY, "benchmark"));
            CommandResult cr = db.command(s);

            // enable sharding on each collection
            cr = db.command(BasicDBObjectBuilder.start("shardCollection", "benchmark.users").push("key")
                    .add("_id", 1).pop().get());
            if (Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY,
                    MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT)) == false) {
                cr = db.command(BasicDBObjectBuilder.start("shardCollection", "benchmark.resources").push("key")
                        .add("walluserid", 1).pop().get());
                cr = db.command(BasicDBObjectBuilder.start("shardCollection", "benchmark.manipulation")
                        .push("key").add("rid", 1).pop().get());
            } else {
                cr = db.command(BasicDBObjectBuilder.start("shardCollection", "benchmark.resources").push("key")
                        .add("_id", 1).pop().get());
            }
            //force move a chunk   
            //BasicDBObject mov = new BasicDBObject("moveChunk","benchmark.users");
            //BasicDBObject mo2 = new BasicDBObject("_id", 1); //this is the chunkid not the userid
            //mov.put("find", mo2);
            //mov.put("to", "shard0001");
            //CommandResult result2 = mongo.getDB("admin").command(mov);
            //System.out.println(result2);
            //check if migration is happening
            //            com.mongodb.DB db2 = mongo.getDB("config");
            //            DBCollection cl = db2.getCollection("locks");
            //            DBObject q = new BasicDBObject().append("_id", "balancer");
            //            DBObject qres = cl.findOne(q);
            //            while( Integer.parseInt(qres.get("state").toString()) == 1 )
            //               System.out.println("still migrating");
        }

        // create indexes on collection
        db = mongo.getDB(database);
        collection = db.getCollection("users");
        collection.createIndex(new BasicDBObject("users.wallResources", 1)); // create
        // index
        // on
        collection = db.getCollection("resources");
        collection.createIndex(new BasicDBObject("walluserid", 1)); // create
        // index
        // on
        // "i",
        // ascending
        if (Boolean.parseBoolean(props.getProperty(MONGODB_MANIPULATION_ARRAY_PROPERTY,
                MONGODB_MANIPULATION_ARRAY_PROPERTY_DEFAULT)) == false) {
            collection = db.getCollection("manipulation");
            collection.createIndex(new BasicDBObject("mid", 1));
            collection.createIndex(new BasicDBObject("rid", 1)); // create
            // index
            // on
            // "i",
            // ascending
        } else {
            collection.createIndex(new BasicDBObject("resources.Manipulations", 1)); // create index on
            // "i", ascending
        }

    } catch (Exception e) {
        System.out.println(e.toString());
        return;
    } finally {
        if (db != null) {
            db.requestDone();
        }
    }
}

From source file:mvm.rya.indexing.mongodb.GeoMongoDBStorageStrategy.java

License:Apache License

public void createIndices(DBCollection coll) {
    coll.createIndex("{" + GEO + " : \"2dsphere\"");
}

From source file:mvm.rya.mongodb.dao.SimpleMongoDBNamespaceManager.java

License:Apache License

@Override
public void createIndices(DBCollection coll) {
    coll.createIndex(PREFIX);
    coll.createIndex(NAMESPACE);
}