com.mongodb.client.model.IndexOptions Java Examples
The following examples show how to use
com.mongodb.client.model.IndexOptions.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoAccessTokenRepository.java From graviteeio-access-management with Apache License 2.0 | 7 votes |
@PostConstruct public void init() { accessTokenCollection = mongoOperations.getCollection("access_tokens", AccessTokenMongo.class); // one field index super.createIndex(accessTokenCollection, new Document(FIELD_TOKEN, 1)); super.createIndex(accessTokenCollection, new Document(FIELD_CLIENT_ID, 1)); super.createIndex(accessTokenCollection, new Document(FIELD_AUTHORIZATION_CODE, 1)); super.createIndex(accessTokenCollection, new Document(FIELD_SUBJECT, 1)); // two fields index super.createIndex(accessTokenCollection, new Document(FIELD_CLIENT_ID, 1).append(FIELD_SUBJECT, 1)); // expire after index super.createIndex(accessTokenCollection, new Document(FIELD_RESET_TIME, 1), new IndexOptions().expireAfter(0L, TimeUnit.SECONDS)); }
Example #2
Source File: MongoSession.java From presto with Apache License 2.0 | 6 votes |
private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document metadata = new Document(TABLE_NAME_KEY, tableName); ArrayList<Document> fields = new ArrayList<>(); if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) { fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument()); } fields.addAll(columns.stream() .map(MongoColumnHandle::getDocument) .collect(toList())); metadata.append(FIELDS_KEY, fields); MongoCollection<Document> schema = db.getCollection(schemaCollection); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); }
Example #3
Source File: AggregateMergeTest.java From mongodb-aggregate-query-support with Apache License 2.0 | 6 votes |
@Test public void mustNotOverwriteExistingDocuments() throws JsonProcessingException { String employeeCollection = RandomStringUtils.randomAlphabetic(10); String orgArchiveColl = RandomStringUtils.randomAlphabetic(10); List<Employee> originalEmployees = addEmployeeDocuments(employeeCollection, EMPLOYEE_DOCS); MongoCollection<Document> employeeColl = mongoTemplate.getCollection(employeeCollection); assertEquals(employeeColl.countDocuments(), originalEmployees.size()); List<OrgArchiveEntry> orgArchiveEntries = addOrgArchiveEntries(orgArchiveColl, ORG_ARCHIVE_DOCS); MongoCollection<Document> orgArchiveCollection = mongoTemplate.getCollection(orgArchiveColl); assertEquals(orgArchiveCollection.countDocuments(), orgArchiveEntries.size()); orgArchiveCollection.createIndex(BsonDocument.parse("{ \"fiscalYear\": 1, \"dept\": 1 }"), new IndexOptions().unique(true)); zooEmployeeRepository.updateOrgArchiveInsertOnly(employeeCollection, orgArchiveColl); assertEquals(orgArchiveCollection.countDocuments(), orgArchiveEntries.size() + 2); Query query = new Query(Criteria.where("fiscalYear").is(2019)); List<OrgArchiveEntry> newArchiveEntries = mongoTemplate.find(query, OrgArchiveEntry.class, orgArchiveColl); assertEquals(newArchiveEntries.size(), 2); }
Example #4
Source File: MongoCollectionIndexEnsure.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException { MongoDatabase db = getMongoDatabase( _session, argStruct ); String collection = getNamedStringParam(argStruct, "collection", null); if ( collection == null ) throwException(_session, "please specify a 'collection' parameter"); cfData keys = getNamedParam(argStruct, "keys", null ); if ( keys == null ) throwException(_session, "please specify 'keys' parameter"); String index = getNamedStringParam(argStruct, "name", null ); if ( index == null ) throwException(_session, "please specify 'index' parameter"); try{ db.getCollection( collection ).createIndex( getDocument(keys), new IndexOptions().background( true ).unique( getNamedBooleanParam(argStruct, "unique", false) ) ); return cfBooleanData.TRUE; } catch (Exception me){ throwException(_session, me.getMessage()); return null; } }
Example #5
Source File: NamedQueryRegistration.java From epcis with Apache License 2.0 | 6 votes |
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) { MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery", BsonDocument.class); MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData", BsonDocument.class); BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first(); if (existingDoc == null) { BsonDocument bson = PollParameters.asBsonDocument(p); bson.put("name", new BsonString(name)); bson.put("description", new BsonString(description)); namedEventQueryCollection.insertOne(bson); } else { return false; } // Create Index with the given NamedEventQuery name and background option IndexOptions indexOptions = new IndexOptions().name(name).background(true); BsonDocument indexDocument = makeIndexObject(p); eventDataCollection.createIndex(indexDocument, indexOptions); Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. "); return true; }
Example #6
Source File: NamedQueryRegistration.java From epcis with Apache License 2.0 | 6 votes |
private boolean addNamedEventQueryToDB(String name, String description, PollParameters p) { MongoCollection<BsonDocument> namedEventQueryCollection = Configuration.mongoDatabase.getCollection("NamedEventQuery", BsonDocument.class); MongoCollection<BsonDocument> eventDataCollection = Configuration.mongoDatabase.getCollection("EventData", BsonDocument.class); BsonDocument existingDoc = namedEventQueryCollection.find(new BsonDocument("name", new BsonString(name))).first(); if (existingDoc == null) { BsonDocument bson = PollParameters.asBsonDocument(p); bson.put("name", new BsonString(name)); bson.put("description", new BsonString(description)); namedEventQueryCollection.insertOne(bson); } else { return false; } // Create Index with the given NamedEventQuery name and background option IndexOptions indexOptions = new IndexOptions().name(name).background(true); BsonDocument indexDocument = makeIndexObject(p); eventDataCollection.createIndex(indexDocument, indexOptions); Configuration.logger.log(Level.INFO, "NamedEventQuery: " + name + " is added to DB. "); return true; }
Example #7
Source File: MongoDBSessionDataStorage.java From pippo with Apache License 2.0 | 6 votes |
/** * Create TTL index * * @param idleTime idle time in seconds * @see <a href="https://docs.mongodb.com/manual/core/index-ttl/">Mongo docs</a> */ private void createIndex(long idleTime) { try { this.sessions.createIndex( new Document(SESSION_TTL, 1), new IndexOptions() .expireAfter(idleTime, TimeUnit.SECONDS) .name(SESSION_INDEX_NAME)); } catch (MongoException ex) {//update idle time this.sessions.dropIndex(SESSION_INDEX_NAME); this.sessions.createIndex( new Document(SESSION_TTL, 1), new IndexOptions() .expireAfter(idleTime, TimeUnit.SECONDS) .name(SESSION_INDEX_NAME)); } }
Example #8
Source File: ProfilingWriter.java From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 | 6 votes |
public ProfilingWriter(BlockingQueue<ProfilingEntry> jobQueue) { this.jobQueue = jobQueue; serverDto = ConfigReader.getCollectorServer(); runningSince = new Date(); final MongoDbAccessor mongo = getMongoDbAccessor(); try { final MongoCollection<Document> profileCollection = getProfileCollection(mongo); IndexOptions indexOptions = new IndexOptions(); indexOptions.background(true); LOG.info("Create index {ts:-1, lbl:1} in the background if it does not yet exists"); profileCollection.createIndex(new BasicDBObject("ts",-1).append("lbl", 1), indexOptions); LOG.info("Create index {adr:1, db:1, ts:-1} in the background if it does not yet exists"); profileCollection.createIndex(new BasicDBObject("adr",1).append("db",1).append("ts", -1), indexOptions); LOG.info("ProfilingWriter is ready at {}", serverDto.getHosts()); } catch (MongoException e) { LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e); } }
Example #9
Source File: ProfilingWriter.java From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 | 6 votes |
private void init(MongoDbAccessor mongo) { LOG.info(">>> init"); try { final MongoCollection<Document> profileCollection = getProfileCollection(mongo); IndexOptions indexOptions = new IndexOptions(); indexOptions.background(true); LOG.info("Create index {ts:-1, lbl:1} in the background if it does not yet exists"); profileCollection.createIndex(new BasicDBObject("ts",-1).append("lbl", 1), indexOptions); LOG.info("Create index {adr:1, db:1, ts:-1} in the background if it does not yet exists"); profileCollection.createIndex(new BasicDBObject("adr",1).append("db",1).append("ts", -1), indexOptions); ApplicationStatusDto.addWebLog("ProfilingWriter is successfully connected to its collector database."); } catch (MongoException e) { LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e); ApplicationStatusDto.addWebLog("ProfilingWriter could not connect to its collector database."); } LOG.info("<<< init"); }
Example #10
Source File: Index.java From ditto with Eclipse Public License 2.0 | 6 votes |
/** * Creates a new {@link IndexModel}, which can be used for creating indices using MongoDB Java drivers. * * @return the created {@link IndexModel} */ public IndexModel toIndexModel() { final IndexOptions options = new IndexOptions() .name(name) .unique(unique) .sparse(sparse) .background(background); if (!partialFilterExpression.isEmpty()) { options.partialFilterExpression(partialFilterExpression); } getExpireAfterSeconds().ifPresent(n -> options.expireAfter(n, TimeUnit.SECONDS)); return new IndexModel(keys, options); }
Example #11
Source File: IndexOptionsMemoryOperation.java From jphp with Apache License 2.0 | 6 votes |
@Override public IndexOptions convert(Environment env, TraceInfo trace, Memory arg) throws Throwable { if (arg.isNull()) return null; ArrayMemory arr = arg.toValue(ArrayMemory.class); IndexOptions options = new IndexOptions(); if (arr.containsKey("background")) { options.background(arg.valueOfIndex("background").toBoolean()); } if (arr.containsKey("defaultLanguage")) { options.defaultLanguage(arg.valueOfIndex("defaultLanguage").toString()); } if (arr.containsKey("bits")) { options.bits(arg.valueOfIndex("bits").toInteger()); } if (arr.containsKey("name")) { options.name(arg.valueOfIndex("name").toString()); } if (arr.containsKey("max")) { options.max(arg.valueOfIndex("max").toDouble()); } if (arr.containsKey("min")) { options.min(arg.valueOfIndex("min").toDouble()); } if (arr.containsKey("languageOverride")) { options.languageOverride(arg.valueOfIndex("languageOverride").toString()); } if (arr.containsKey("sparse")) { options.sparse(arg.valueOfIndex("sparse").toBoolean()); } if (arr.containsKey("unique")) { options.unique(arg.valueOfIndex("unique").toBoolean()); } if (arr.containsKey("version")) { options.version(arg.valueOfIndex("version").toInteger()); } if (arr.containsKey("textVersion")) { options.textVersion(arg.valueOfIndex("textVersion").toInteger()); } if (arr.containsKey("sphereVersion")) { options.sphereVersion(arg.valueOfIndex("sphereVersion").toInteger()); } return options; }
Example #12
Source File: IndexOptionsMemoryOperation.java From jphp with Apache License 2.0 | 6 votes |
@Override public Memory unconvert(Environment env, TraceInfo trace, IndexOptions arg) throws Throwable { if (arg == null) return Memory.NULL; ArrayMemory options = ArrayMemory.createHashed(12); options.put("name", arg.getName()); options.put("background", arg.isBackground()); options.put("sparse", arg.isSparse()); options.put("unique", arg.isUnique()); if (arg.getDefaultLanguage() != null) options.put("defaultLanguage", arg.getDefaultLanguage()); if (arg.getBits() != null) options.put("bits", arg.getBits()); if (arg.getMax() != null) options.put("max", arg.getMax()); if (arg.getMin() != null) options.put("min", arg.getMin()); if (arg.getLanguageOverride() != null) options.put("languageOverride", arg.getLanguageOverride()); if (arg.getVersion() != null) options.put("version", arg.getVersion()); if (arg.getTextVersion() != null) options.put("textVersion", arg.getTextVersion()); if (arg.getSphereVersion() != null) options.put("sphereVersion", arg.getSphereVersion()); return options; }
Example #13
Source File: MongoRequestObjectRepository.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@PostConstruct public void init() { requestObjectCollection = mongoOperations.getCollection("request_objects", RequestObjectMongo.class); // one field index super.createIndex(requestObjectCollection, new Document(FIELD_CLIENT, 1)); super.createIndex(requestObjectCollection, new Document(FIELD_DOMAIN, 1)); // expire after index super.createIndex(requestObjectCollection, new Document(FIELD_EXPIRE_AT, 1), new IndexOptions().expireAfter(0L, TimeUnit.SECONDS)); }
Example #14
Source File: ConfigService.java From runelite with BSD 2-Clause "Simplified" License | 5 votes |
@Autowired public ConfigService( MongoClient mongoClient, @Value("${mongo.database}") String databaseName ) { MongoDatabase database = mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = database.getCollection("config"); this.mongoCollection = collection; // Create unique index on _userId IndexOptions indexOptions = new IndexOptions().unique(true); collection.createIndex(Indexes.ascending("_userId"), indexOptions); }
Example #15
Source File: MongoDocumentDb.java From mdw with Apache License 2.0 | 5 votes |
public static void createMongoDocIdIndex(String collectionName) { try { MongoDatabase mongoDb = getMongoDb(); if (mongoDb != null) { IndexOptions indexOptions = new IndexOptions().unique(true).background(true).name("document_id_1"); MongoCollection<org.bson.Document> collection = mongoDb.getCollection(collectionName); String indexName = collection.createIndex(Indexes.ascending("document_id"), indexOptions); LoggerUtil.getStandardLogger().mdwDebug("Created Index : " + indexName + " on collection : " + collectionName); collectionDocIdIndexed.putIfAbsent(collectionName, true); } } catch (Exception e) { LoggerUtil.getStandardLogger().info("Failed to create index for 'document_id' on " + collectionName + " collection", e); } }
Example #16
Source File: MongoCompensableLogger.java From ByteTCC with GNU Lesser General Public License v3.0 | 5 votes |
private void createTransactionsGlobalTxKeyIndexIfNecessary() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> transactions = database.getCollection(CONSTANTS_TB_TRANSACTIONS); ListIndexesIterable<Document> transactionIndexList = transactions.listIndexes(); boolean transactionIndexExists = false; MongoCursor<Document> transactionCursor = null; try { transactionCursor = transactionIndexList.iterator(); while (transactionIndexExists == false && transactionCursor.hasNext()) { Document document = transactionCursor.next(); Boolean unique = document.getBoolean("unique"); Document key = (Document) document.get("key"); boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL); boolean lengthEquals = key.size() == 1; transactionIndexExists = lengthEquals && globalExists; if (transactionIndexExists && (unique == null || unique == false)) { throw new IllegalStateException(); } } } finally { IOUtils.closeQuietly(transactionCursor); } if (transactionIndexExists == false) { Document index = new Document(CONSTANTS_FD_GLOBAL, 1); transactions.createIndex(index, new IndexOptions().unique(true)); } }
Example #17
Source File: MongoCompensableLock.java From ByteTCC with GNU Lesser General Public License v3.0 | 5 votes |
private void createLocksIndexIfNecessary() { String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_"); MongoDatabase database = this.mongoClient.getDatabase(databaseName); MongoCollection<Document> locks = database.getCollection(CONSTANTS_TB_LOCKS); ListIndexesIterable<Document> lockIndexList = locks.listIndexes(); boolean transactionIndexExists = false; MongoCursor<Document> lockCursor = null; try { lockCursor = lockIndexList.iterator(); while (transactionIndexExists == false && lockCursor.hasNext()) { Document document = lockCursor.next(); Boolean unique = document.getBoolean("unique"); Document key = (Document) document.get("key"); boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL); boolean lengthEquals = key.size() == 1; transactionIndexExists = lengthEquals && globalExists; if (transactionIndexExists && (unique == null || unique == false)) { throw new IllegalStateException(); } } } finally { IOUtils.closeQuietly(lockCursor); } if (transactionIndexExists == false) { Document index = new Document(CONSTANTS_FD_GLOBAL, 1); locks.createIndex(index, new IndexOptions().unique(true)); } }
Example #18
Source File: MongoCollectionImpl.java From mongo-java-driver-rx with Apache License 2.0 | 5 votes |
@Override public Observable<String> createIndex(final Bson key, final IndexOptions options) { return RxObservables.create(Observables.observe(new Block<SingleResultCallback<String>>() { @Override public void apply(final SingleResultCallback<String> callback) { wrapped.createIndex(key, options, callback); } }), observableAdapter); }
Example #19
Source File: MongoImpl.java From core-ng-project with Apache License 2.0 | 5 votes |
@Override public void createIndex(String collection, Bson keys, IndexOptions options) { var watch = new StopWatch(); try { database().getCollection(collection).createIndex(keys, options); } finally { logger.info("createIndex, collection={}, keys={}, options={}, elapsed={}", collection, keys, options, watch.elapsed()); } }
Example #20
Source File: MongoJobRepository.java From edison-microservice with Apache License 2.0 | 5 votes |
@Override protected final void ensureIndexes() { IndexOptions options = new IndexOptions().background(true); collection().createIndex(Indexes.compoundIndex(Indexes.ascending(JobStructure.JOB_TYPE.key()), Indexes.descending(JobStructure.STARTED.key())), options); collection().createIndex(Indexes.ascending(JobStructure.STARTED.key()), options); collection().createIndex(Indexes.ascending(JobStructure.LAST_UPDATED.key(), JobStructure.STOPPED.key()), options); }
Example #21
Source File: MongoDBTargetIT.java From datacollector with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { MongoDatabase db = mongo.getDatabase(DATABASE_NAME); db.createCollection(TEST_WRITE_COLLECTION); db.createCollection(UNIQUE_KEY_EXCEPTION_COLLECTION); testWriteCollection = db.getCollection(TEST_WRITE_COLLECTION); testWriteCollection.createIndex(Indexes.text("name"), new IndexOptions().unique(true)); }
Example #22
Source File: MongoCollectionImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@Override public Publisher<String> createIndex(final Bson key, final IndexOptions options) { return new ObservableToPublisher<String>(com.mongodb.async.client.Observables.observe( new Block<com.mongodb.async.SingleResultCallback<String>>() { @Override public void apply(final com.mongodb.async.SingleResultCallback<String> callback) { wrapped.createIndex(key, options, callback); } })); }
Example #23
Source File: AggregationTest.java From morphia with Apache License 2.0 | 5 votes |
@Test public void testPlanCacheStats() { checkMinServerVersion(4.2); List<Document> list = List.of( parse("{ '_id' : 1, 'item' : 'abc', 'price' : NumberDecimal('12'), 'quantity' : 2, 'type': 'apparel' }"), parse("{ '_id' : 2, 'item' : 'jkl', 'price' : NumberDecimal('20'), 'quantity' : 1, 'type': 'electronics' }"), parse("{ '_id' : 3, 'item' : 'abc', 'price' : NumberDecimal('10'), 'quantity' : 5, 'type': 'apparel' }"), parse("{ '_id' : 4, 'item' : 'abc', 'price' : NumberDecimal('8'), 'quantity' : 10, 'type': 'apparel' }"), parse("{ '_id' : 5, 'item' : 'jkl', 'price' : NumberDecimal('15'), 'quantity' : 15, 'type': 'electronics' }")); MongoCollection<Document> orders = getDatabase().getCollection("orders"); orders.insertMany(list); Assert.assertNotNull(orders.createIndex(new Document("item", 1))); Assert.assertNotNull(orders.createIndex(new Document("item", 1) .append("quantity", 1))); Assert.assertNotNull(orders.createIndex(new Document("item", 1) .append("price", 1), new IndexOptions() .partialFilterExpression(new Document("price", new Document("$gte", 10))))); Assert.assertNotNull(orders.createIndex(new Document("quantity", 1))); Assert.assertNotNull(orders.createIndex(new Document("quantity", 1) .append("type", 1))); orders.find(parse(" { item: 'abc', price: { $gte: NumberDecimal('10') } }")); orders.find(parse(" { item: 'abc', price: { $gte: NumberDecimal('5') } }")); orders.find(parse(" { quantity: { $gte: 20 } } ")); orders.find(parse(" { quantity: { $gte: 5 }, type: 'apparel' } ")); List<Document> stats = getDs().aggregate(Order.class) .planCacheStats() .execute(Document.class, new AggregationOptions() .readConcern(ReadConcern.LOCAL)) .toList(); Assert.assertNotNull(stats); }
Example #24
Source File: MongoCollectionImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@Override public Publisher<String> createIndex(final ClientSession clientSession, final Bson key, final IndexOptions options) { return new ObservableToPublisher<String>(com.mongodb.async.client.Observables.observe( new Block<com.mongodb.async.SingleResultCallback<String>>() { @Override public void apply(final com.mongodb.async.SingleResultCallback<String> callback) { wrapped.createIndex(clientSession.getWrapped(), key, options, callback); } })); }
Example #25
Source File: MongoSession.java From presto with Apache License 2.0 | 5 votes |
private Document getTableMetadata(SchemaTableName schemaTableName) throws TableNotFoundException { String schemaName = toRemoteSchemaName(schemaTableName.getSchemaName()); String tableName = toRemoteTableName(schemaName, schemaTableName.getTableName()); MongoDatabase db = client.getDatabase(schemaName); MongoCollection<Document> schema = db.getCollection(schemaCollection); Document doc = schema .find(new Document(TABLE_NAME_KEY, tableName)).first(); if (doc == null) { if (!collectionExists(db, tableName)) { throw new TableNotFoundException(schemaTableName); } else { Document metadata = new Document(TABLE_NAME_KEY, tableName); metadata.append(FIELDS_KEY, guessTableFields(schemaName, tableName)); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); return metadata; } } return doc; }
Example #26
Source File: ChangeEntryIndexDao.java From mongobee with Apache License 2.0 | 5 votes |
public void createRequiredUniqueIndex(MongoCollection<Document> collection) { collection.createIndex(new Document() .append(ChangeEntry.KEY_CHANGEID, 1) .append(ChangeEntry.KEY_AUTHOR, 1), new IndexOptions().unique(true) ); }
Example #27
Source File: Repositories.java From immutables with Apache License 2.0 | 5 votes |
protected final FluentFuture<Void> doIndex( final Constraints.Constraint fields, final IndexOptions options) { return submit(new Callable<Void>() { @Override public Void call() { collection().createIndex(convertToIndex(fields), options); return null; } }); }
Example #28
Source File: MongoStorageAdapter.java From Prism with MIT License | 5 votes |
/** * Establish connections to the database * * @return Whether we could connect properly */ @Override public boolean connect() throws Exception { ServerAddress address = new ServerAddress(Prism.getInstance().getConfig().getStorageCategory().getAddress(), ServerAddress.defaultPort()); MongoCredential credential = MongoCredential.createCredential( Prism.getInstance().getConfig().getStorageCategory().getUsername(), databaseName, Prism.getInstance().getConfig().getStorageCategory().getPassword().toCharArray() ); CodecRegistry codecRegistry = CodecRegistries.fromRegistries( MongoClient.getDefaultCodecRegistry(), CodecRegistries.fromCodecs(new PrimitiveArrayCodec()) ); mongoClient = new MongoClient(address, credential, MongoClientOptions.builder().codecRegistry(codecRegistry).build()); // @todo support auth: boolean auth = db.authenticate(myUserName, myPassword); // Connect to the database database = mongoClient.getDatabase(databaseName); // Create indexes try { getCollection(collectionEventRecordsName).createIndex( new Document("Location.X", 1).append("Location.Z", 1).append("Location.Y", 1).append("Created", -1)); getCollection(collectionEventRecordsName).createIndex(new Document("Created", -1).append("EventName", 1)); // TTL IndexOptions options = new IndexOptions().expireAfter(0L, TimeUnit.SECONDS); getCollection(collectionEventRecordsName).createIndex(new Document("Expires", 1), options); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Example #29
Source File: MongoUtil.java From render with GNU General Public License v2.0 | 5 votes |
public static void createIndex(final MongoCollection<Document> collection, final Document keys, final IndexOptions options) { LOG.debug("createIndex: entry, collection={}, keys={}, options={}", MongoUtil.fullName(collection), keys.toJson(), toJson(options)); collection.createIndex(keys, options); LOG.debug("createIndex: exit"); }
Example #30
Source File: ExampleSlowOpsCache.java From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 | 5 votes |
private ExampleSlowOpsCache(){ cache = new HashSet<>(); serverDto = ConfigReader.getCollectorServer(); readLock = globalLock.readLock(); writeLock = globalLock.writeLock(); final MongoDbAccessor mongo = new MongoDbAccessor(serverDto.getAdminUser(), serverDto.getAdminPw(), serverDto.getSsl(), serverDto.getHosts()); try { exampleCollection = getExampleCollection(mongo); final IndexOptions indexOptions = new IndexOptions(); indexOptions.background(true); //index for retrieval by fingerprint (don't make it unique in case of collisions by the hashing algorithm) LOG.info("Create index {fp:1} in the background if it does not yet exists"); exampleCollection.createIndex(new BasicDBObject("fp", 1), indexOptions); //index for removing old entries // e.g. when the slow ops collection is a capped collection // then entries older than the oldest slow op can be removed from the example collection // (the entry may be added automatically anew if the corresponding query is collected again) LOG.info("Create index {ts:1} in the background if it does not yet exists"); exampleCollection.createIndex(new BasicDBObject("ts", 1), indexOptions); loadCache(exampleCollection); LOG.info("ExampleSlowOpsCache is ready at {}", serverDto.getHosts()); } catch (MongoException e) { LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e); } }