/** * Makes an index to enforce unique constraint. * @return {@code this} indexer for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final I unique() { options.unique(true); return (I) this; }
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); }
private static void createIndex(MongoConnection mongoConnection) { final IndexOptions indexOptions = new IndexOptions() .name(INDEX_NAME) .unique(true); mongoConnection.getMongoDatabase() .getCollection(COLLECTION_NAME) .createIndex(Indexes.ascending("name"), indexOptions); }
private Document getTableMetadata(SchemaTableName schemaTableName) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = 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(schemaTableName)); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); return metadata; } } return doc; }
.unique(true); collection.createIndex(Indexes.ascending("name"), indexOptions);
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)); } }
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)); } }
private void checkCreateIndex(@Nullable final ClientSession clientSession) { if (!checkedIndexes) { if (collectionIsEmpty(clientSession, filesCollection.withDocumentClass(Document.class).withReadPreference(primary()))) { Document filesIndex = new Document("filename", 1).append("uploadDate", 1); if (!hasIndex(clientSession, filesCollection.withReadPreference(primary()), filesIndex)) { createIndex(clientSession, filesCollection, filesIndex, new IndexOptions()); } Document chunksIndex = new Document("files_id", 1).append("n", 1); if (!hasIndex(clientSession, chunksCollection.withReadPreference(primary()), chunksIndex)) { createIndex(clientSession, chunksCollection, chunksIndex, new IndexOptions().unique(true)); } } checkedIndexes = true; } }
@SuppressWarnings("deprecation") com.mongodb.client.model.IndexOptions convert(final IndexOptions options, final boolean background) { if (options.dropDups()) { LOG.warn("Support for dropDups has been removed from the server. Please remove this setting."); } com.mongodb.client.model.IndexOptions indexOptions = new com.mongodb.client.model.IndexOptions() .background(options.background() || background) .sparse(options.sparse()) .unique(options.unique()); if (!options.language().equals("")) { indexOptions.defaultLanguage(options.language()); } if (!options.languageOverride().equals("")) { indexOptions.languageOverride(options.languageOverride()); } if (!options.name().equals("")) { indexOptions.name(options.name()); } if (options.expireAfterSeconds() != -1) { indexOptions.expireAfter((long) options.expireAfterSeconds(), TimeUnit.SECONDS); } if (!options.partialFilter().equals("")) { indexOptions.partialFilterExpression(Document.parse(options.partialFilter())); } if (!options.collation().locale().equals("")) { indexOptions.collation(convert(options.collation())); } return indexOptions; }
ops = ops.unique((Boolean) indexOptions.get("unique"));
@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; }
/** * Makes an index to enforce unique constraint. * @return {@code this} indexer for chained invocation */ // safe unchecked: we expect I to be a self type @SuppressWarnings("unchecked") public final I unique() { options.unique(true); return (I) this; }
ops = ops.unique((Boolean) indexOptions.get("unique"));
private void createCollectionAndUniqueIndexIfNotExists(MongoDatabase db) { Document indexKeys = new Document(KEY_PROP_NAME, INDEX_SORT_ASC); IndexOptions indexOptions = new IndexOptions().unique(true).name("mongobeelock_key_idx"); db.getCollection(lockCollectionName).createIndex(indexKeys, indexOptions); }
private void createCollectionAndUniqueIndexIfNotExists(MongoDatabase db) { Document indexKeys = new Document(KEY_PROP_NAME, INDEX_SORT_ASC); IndexOptions indexOptions = new IndexOptions().unique(true).name("mongobeelock_key_idx"); db.getCollection(lockCollectionName).createIndex(indexKeys, indexOptions); }
/** * Ensure that expected collection indexes exist. * * @throws SiteWhereException */ protected void ensureIndexes() throws SiteWhereException { getMongoClient().getUsersCollection().createIndex(new Document(MongoUser.PROP_USERNAME, 1), new IndexOptions().unique(true)); getMongoClient().getAuthoritiesCollection().createIndex(new Document(MongoGrantedAuthority.PROP_AUTHORITY, 1), new IndexOptions().unique(true)); }
/** * Ensure that expected collection indexes exist. * * @throws SiteWhereException */ protected void ensureIndexes() throws SiteWhereException { getMongoClient().getSchedulesCollection().createIndex(new Document(MongoSchedule.PROP_TOKEN, 1), new IndexOptions().unique(true)); getMongoClient().getScheduledJobsCollection().createIndex(new Document(MongoScheduledJob.PROP_TOKEN, 1), new IndexOptions().unique(true)); }
@Override public void ensureIndexes() { Document index = new Document(); index.append(Tag.PROJECT_ID, 1); index.append(Tag.LABEL, 1); getCollection().createIndex(index, new IndexOptions().unique(true)); }
@Override public void ensureIndexes(MongoCollection<Document> eventsCollection, MongoCollection<Document> snapshotsCollection) { super.ensureIndexes(eventsCollection, snapshotsCollection); //prevents duplicate commits eventsCollection.createIndex(new BasicDBObject(eventConfiguration().aggregateIdentifierProperty(), ORDER_ASC) .append(commitEntryConfiguration.firstSequenceNumberProperty(), ORDER_ASC), new IndexOptions().unique(true).name("uniqueAggregateStartIndex")); } }
@Test public void testQueryWithSubdocumentIndex() throws Exception { collection.createIndex(json("action: {actionId: 1}"), new IndexOptions().unique(true)); collection.insertOne(json("action: {actionId: 1}, value: 'a'")); collection.insertOne(json("action: {actionId: 2}, value: 'b'")); collection.insertOne(json("action: {actionId: 3}, value: 'c'")); Document foundWithNestedDocument = collection.find(json("action: {actionId: 2}")).first(); assertThat(foundWithNestedDocument.get("value")).isEqualTo("b"); Document foundWithDotNotation = collection.find(json("'action.actionId': 2")).first(); assertThat(foundWithDotNotation.get("value")).isEqualTo("b"); }