List of usage examples for com.mongodb DBCollection createIndex
public void createIndex(final DBObject keys, @Nullable final String name, final boolean unique)
From source file:com.mycompany.bean.PlytaService.java
public List<Plyta> searchByTytul(String DBName, String CollectionName, String paramTytul) throws Exception { List<Plyta> plyty = new ArrayList(); try {// w w w . j a v a 2 s. c o m DBCollection collection = getConnection(DBName, CollectionName); BasicDBObject TytulIndex = new BasicDBObject(); TytulIndex.put("tytul", 1); collection.createIndex(TytulIndex, "TytulIndex", true); // tworzy index jeeli takiego nie ma BasicDBObject query = new BasicDBObject(); query.append("tytul", paramTytul); DBCursor cur = collection.find(query); DBObject o; Plyta p; while (cur.hasNext()) { p = new Plyta(); o = cur.next(); p.setTytul((String) o.get("tytul")); p.setAutor((List<String>) o.get("autor")); p.setLiczbaUtworow((Integer) o.get("liczbaUtworow")); p.setWytwornia((List<String>) o.get("wytwornia")); p.setRokWydania((Integer) o.get("rokWydania")); p.setProducent((String) o.get("producent")); p.setGatunek((List<String>) o.get("gatunek")); p.setDlugosc((String) o.get("dlugosc")); p.setSingle((List<String>) o.get("single")); p.setNagrody((List<String>) o.get("nagrody")); p.setRodzajAlbumu((String) o.get("rodzajAlbumu")); p.setUtwory((List<Utwor>) o.get("utwory")); plyty.add(p); } log.log(Level.INFO, "Zapytanie wykonane poprawnie"); } catch (Exception e) { log.log(Level.SEVERE, "Blad wykonania zapytania"); } return plyty; }
From source file:com.norconex.collector.core.data.store.impl.mongo.BaseMongoSerializer.java
License:Apache License
protected final void ensureIndex(DBCollection coll, boolean unique, String... fields) { BasicDBObject fieldsObject = new BasicDBObject(); for (String field : fields) { fieldsObject.append(field, 1);//from ww w.j a va2s .c om } coll.createIndex(fieldsObject, null, unique); }
From source file:edu.stanford.epad.common.util.MongoDBOperations.java
License:Open Source License
/** * Create indexes (only if they don't already exist) * @param collection// ww w .j a v a 2 s . c om * @throws Exception */ public static void createIndexes(String collection) throws Exception { try { int count = 0; DB db = MongoDBOperations.getMongoDB(); if (db == null) { log.warning("No connection to Mongo DB"); return; } DBCollection dbColl = db.getCollection(collection); BasicDBObject dbObj = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", 1); dbColl.createIndex(dbObj, "uid_idx", true); // Does not create index, if it already exists dbObj = new BasicDBObject("ImageAnnotationCollection.person.name.value", 1); dbColl.createIndex(dbObj, "patientname_idx", false); // Does not create index, if it already exists dbObj = new BasicDBObject("ImageAnnotationCollection.person.id.value", 1); dbColl.createIndex(dbObj, "patientid_idx", false); // Does not create index, if it already exists } catch (Exception e) { log.warning("Error querying mongodb:", e); throw e; } }
From source file:edu.stanford.epad.common.util.MongoDBOperations.java
License:Open Source License
/** * Converts and saves an annotation to mongoDB * @param annotationID// w w w . j av a 2 s .c om * @param aimXML * @param collection * @throws Exception */ public static void saveAnnotationToMongo(String annotationID, String aimXML, String collection) throws Exception { try { DB db = MongoDBOperations.getMongoDB(); if (db == null) { log.warning("No connection to Mongo DB"); return; } if (aimXML == null || aimXML.trim().length() == 0) return; String jsonString = XML.toJSONObject(aimXML).toString(0); ; if (jsonString == null) throw new Exception("Error converting to json"); DBCollection dbColl = db.getCollection(collection); BasicDBObject dbObj = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", 1); dbColl.createIndex(dbObj, "uid_idx", true); // Does not create index, if it already exists BasicDBObject query = new BasicDBObject(); query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID); DBObject dbObject = (DBObject) JSON.parse(jsonString); DBCursor cursor = dbColl.find(query); if (cursor.count() > 0) { log.info("Updating existing annotation in mongoDB:" + annotationID + " in " + collection); dbColl.update(query, dbObject, true, false); } else { log.info("Creating new annotation in mongoDB:" + annotationID + " in " + collection); dbColl.insert(dbObject); } } catch (Exception e) { log.warning("Error saving AIM to mongodb:", e); throw e; } }
From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java
License:Open Source License
protected void createSchemaForClass(AbstractClassMetaData cmd, DB db) { if (cmd.isEmbeddedOnly() || cmd.getPersistenceModifier() != ClassPersistenceModifier.PERSISTENCE_CAPABLE) { // No table required here return;//w ww . ja v a 2 s. c o m } if (cmd instanceof ClassMetaData && ((ClassMetaData) cmd).isAbstract()) { // No table required here return; } StoreData storeData = storeMgr.getStoreDataForClass(cmd.getFullClassName()); Table table = null; if (storeData != null) { table = storeData.getTable(); } else { table = new CompleteClassTable(storeMgr, cmd, null); } String collectionName = table.getName(); DBCollection collection = null; if (isAutoCreateTables() && !db.collectionExists(collectionName)) { // Create collection (if not existing) if (cmd.hasExtension(MongoDBStoreManager.CAPPED_SIZE_EXTENSION_NAME)) { Set<String> collNames = db.getCollectionNames(); if (!collNames.contains(collectionName)) { // Collection specified as "capped" with a size and doesn't exist so create it DBObject options = new BasicDBObject(); options.put("capped", "true"); Long size = Long .valueOf(cmd.getValueForExtension(MongoDBStoreManager.CAPPED_SIZE_EXTENSION_NAME)); options.put("size", size); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClass", cmd.getFullClassName(), collectionName)); } db.createCollection(collectionName, options); } else { DBObject options = new BasicDBObject(); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClass", cmd.getFullClassName(), collectionName)); } collection = db.createCollection(collectionName, options); } } else { DBObject options = new BasicDBObject(); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug( Localiser.msg("MongoDB.Schema.CreateClass", cmd.getFullClassName(), collectionName)); } collection = db.createCollection(collectionName, options); } } if (autoCreateConstraints) { // Create indexes if (collection == null && !db.getCollectionNames().contains(collectionName)) { NucleusLogger.DATASTORE_SCHEMA.warn( "Cannot create constraints for " + cmd.getFullClassName() + " since collection of name " + collectionName + " doesn't exist (enable autoCreateTables?)"); return; } else if (collection == null) { collection = db.getCollection(collectionName); } // Class-level indexes NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractClassMetaData theCmd = cmd; while (theCmd != null) { IndexMetaData[] clsIdxMds = theCmd.getIndexMetaData(); if (clsIdxMds != null) { for (int i = 0; i < clsIdxMds.length; i++) { IndexMetaData idxmd = clsIdxMds[i]; DBObject idxObj = getDBObjectForIndex(cmd, idxmd, table); String idxName = namingFactory.getConstraintName(theCmd, idxmd, i); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClassIndex", idxName, collectionName, idxObj)); } collection.createIndex(idxObj, idxName, idxmd.isUnique()); } } UniqueMetaData[] clsUniMds = theCmd.getUniqueMetaData(); if (clsUniMds != null) { for (int i = 0; i < clsUniMds.length; i++) { UniqueMetaData unimd = clsUniMds[i]; DBObject uniObj = getDBObjectForUnique(cmd, unimd, table); String uniName = namingFactory.getConstraintName(theCmd, unimd, i); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClassIndex", uniName, collectionName, uniObj)); } collection.createIndex(uniObj, uniName, true); } } theCmd = theCmd.getSuperAbstractClassMetaData(); } if (cmd.getIdentityType() == IdentityType.APPLICATION) { // Add unique index on PK BasicDBObject query = new BasicDBObject(); int[] pkFieldNumbers = cmd.getPKMemberPositions(); boolean applyIndex = true; for (int i = 0; i < pkFieldNumbers.length; i++) { AbstractMemberMetaData pkMmd = cmd .getMetaDataForManagedMemberAtAbsolutePosition(pkFieldNumbers[i]); if (storeMgr.isStrategyDatastoreAttributed(cmd, pkFieldNumbers[i])) { applyIndex = false; break; } else if (pkMmd.getUniqueMetaData() != null) { applyIndex = false; break; } MemberColumnMapping mapping = table.getMemberColumnMappingForMember(pkMmd); Column[] cols = mapping.getColumns(); String colName = cols[0].getName(); // TODO Support multicolumn PK fields query.append(colName, 1); } if (applyIndex) { String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug( Localiser.msg("MongoDB.Schema.CreateClassIndex", pkName, collectionName, query)); } collection.createIndex(query, pkName, true); } } else if (cmd.getIdentityType() == IdentityType.DATASTORE) { if (storeMgr.isStrategyDatastoreAttributed(cmd, -1)) { // Using builtin "_id" field so nothing to do } else { BasicDBObject query = new BasicDBObject(); query.append(table.getDatastoreIdColumn().getName(), 1); String pkName = (cmd.getPrimaryKeyMetaData() != null ? cmd.getPrimaryKeyMetaData().getName() : cmd.getName() + "_PK"); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug( Localiser.msg("MongoDB.Schema.CreateClassIndex", pkName, collectionName, query)); } collection.createIndex(query, pkName, true); } } // Column-level indexes Set<MemberColumnMapping> mappings = table.getMemberColumnMappings(); for (MemberColumnMapping mapping : mappings) { Column column = mapping.getColumn(0); UniqueMetaData unimd = mapping.getMemberMetaData().getUniqueMetaData(); if (unimd != null) { BasicDBObject query = new BasicDBObject(); query.append(column.getName(), 1); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClassIndex", unimd.getName(), collectionName, query)); } String idxName = unimd.getName(); if (idxName == null) { idxName = namingFactory.getConstraintName(cmd.getName(), mapping.getMemberMetaData(), unimd); } collection.createIndex(query, idxName, true); } else { IndexMetaData idxmd = mapping.getMemberMetaData().getIndexMetaData(); if (idxmd != null) { BasicDBObject query = new BasicDBObject(); query.append(column.getName(), 1); String idxName = namingFactory.getConstraintName(cmd.getName(), mapping.getMemberMetaData(), idxmd); if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) { NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("MongoDB.Schema.CreateClassIndex", idxName, collectionName, query)); } collection.createIndex(query, idxName, idxmd.isUnique()); } } } } }
From source file:org.graylog2.cluster.ClusterConfigServiceImpl.java
License:Open Source License
@VisibleForTesting static DBCollection prepareCollection(final MongoConnection mongoConnection) { DBCollection coll = mongoConnection.getDatabase().getCollection(COLLECTION_NAME); coll.createIndex(DBSort.asc("type"), "unique_type", true); coll.setWriteConcern(WriteConcern.FSYNCED); return coll;//from www . ja va2s . c o m }