下面列出了怎么用com.mongodb.client.model.IndexOptions的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
/**
* 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);
}
@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));
}
@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);
}
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;
}
}
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;
}
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;
}
/**
* 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));
}
}
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);
}
}
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");
}
@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;
}
@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;
}
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;
}
private void createIndex(MongoIndex annotation) {
if (annotation.properties().length == 0) {
throw new ElepyConfigException("No properties specified in MongoIndex");
}
final var indexOptions = new IndexOptions();
if (!isDefault(annotation.text())) {
indexOptions.textVersion(annotation.text());
}
if (!isDefault(annotation.expireAfterSeconds())) {
indexOptions.expireAfter(annotation.expireAfterSeconds(), TimeUnit.SECONDS);
}
if (!isDefault(annotation.name())) {
indexOptions.name(annotation.name());
}
if (!isDefault(annotation.unique())) {
indexOptions.unique(annotation.unique());
}
final var compoundIndex = Indexes.compoundIndex(Arrays
.stream(annotation.properties())
.map(this::createIndexField)
.collect(Collectors.toList()));
mongoCollection.createIndex(compoundIndex, indexOptions);
}
public AbstractOperation(MongoDbAccessor mongoDbAccessor, String db, String collection, String queriedField){
this.mongoDbAccessor = mongoDbAccessor;
mongoCollection = mongoDbAccessor.getMongoDatabase(db).getCollection(collection);
this.queriedField = queriedField;
final IndexOptions options = new IndexOptions();
options.background(false);
mongoCollection.createIndex(new BasicDBObject(queriedField, 1), options);
minId = getMinMax(mongoDbAccessor, queriedField, true);
maxId = getMinMax(mongoDbAccessor, queriedField, false);
}
@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));
}
@PostConstruct
public void init() {
loginAttemptsCollection = mongoOperations.getCollection("login_attempts", LoginAttemptMongo.class);
super.createIndex(loginAttemptsCollection, new Document(FIELD_DOMAIN, 1).append(FIELD_CLIENT, 1).append(FIELD_USERNAME, 1));
// expire after index
super.createIndex(loginAttemptsCollection, new Document(FIELD_RESET_TIME, 1), new IndexOptions().expireAfter(0L, TimeUnit.SECONDS));
}
@PostConstruct
public void init() {
authorizationCodeCollection = mongoOperations.getCollection("authorization_codes", AuthorizationCodeMongo.class);
super.createIndex(authorizationCodeCollection, new Document(FIELD_CODE, 1));
super.createIndex(authorizationCodeCollection, new Document(FIELD_TRANSACTION_ID, 1));
super.createIndex(authorizationCodeCollection, new Document(FIELD_RESET_TIME, 1), new IndexOptions().expireAfter(0l, TimeUnit.SECONDS));
}
@PostConstruct
public void init() {
scopeApprovalsCollection = mongoOperations.getCollection("scope_approvals", ScopeApprovalMongo.class);
super.createIndex(scopeApprovalsCollection, new Document(FIELD_EXPIRES_AT, 1), new IndexOptions().expireAfter(0l, TimeUnit.SECONDS));
super.createIndex(scopeApprovalsCollection, new Document(FIELD_TRANSACTION_ID, 1));
super.createIndex(scopeApprovalsCollection, new Document(FIELD_DOMAIN, 1).append(FIELD_USER_ID, 1));
super.createIndex(scopeApprovalsCollection, new Document(FIELD_DOMAIN, 1).append(FIELD_CLIENT_ID, 1).append(FIELD_USER_ID, 1));
super.createIndex(scopeApprovalsCollection, new Document(FIELD_DOMAIN, 1).append(FIELD_CLIENT_ID, 1).append(FIELD_USER_ID, 1).append(FIELD_SCOPE, 1));
}
@PostConstruct
public void init() {
refreshTokenCollection = mongoOperations.getCollection("refresh_tokens", RefreshTokenMongo.class);
super.createIndex(refreshTokenCollection, new Document(FIELD_TOKEN, 1));
super.createIndex(refreshTokenCollection, new Document(FIELD_SUBJECT, 1));
super.createIndex(refreshTokenCollection, new Document(FIELD_RESET_TIME, 1), new IndexOptions().expireAfter(0L, TimeUnit.SECONDS));
}
@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);
}
@Inject
public DifferConversationStore(MongoDatabase database) {
checkNotNull(database, "database");
this.collection = database.getCollection(COLLECTION_DIFFER_CONVERSATIONS, DifferConversationInfo.class);
this.userConversationStore = new DifferConversationResourceStore();
collection.createIndex(Indexes.ascending(CONVERSATION_ID_FIELD), new IndexOptions().unique(true));
}
@Inject
public UserConversationStore(MongoDatabase database,
IJsonSerialization jsonSerialization,
IDocumentBuilder documentBuilder) {
this.jsonSerialization = jsonSerialization;
RuntimeUtilities.checkNotNull(database, "database");
this.collection = database.getCollection(COLLECTION_USER_CONVERSATIONS);
this.documentBuilder = documentBuilder;
this.userConversationStore = new UserConversationResourceStore();
collection.createIndex(
Indexes.compoundIndex(
Indexes.ascending(INTENT_FIELD),
Indexes.ascending(USER_ID_FIELD)),
new IndexOptions().unique(true));
}
@Inject
public BotTriggerStore(MongoDatabase database,
IJsonSerialization jsonSerialization,
IDocumentBuilder documentBuilder) {
this.jsonSerialization = jsonSerialization;
RuntimeUtilities.checkNotNull(database, "database");
this.collection = database.getCollection(COLLECTION_BOT_TRIGGERS);
this.documentBuilder = documentBuilder;
this.botTriggerStore = new BotTriggerResourceStore();
collection.createIndex(Indexes.ascending(INTENT_FIELD), new IndexOptions().unique(true));
}
@Inject
public PropertiesStore(MongoDatabase database) {
RuntimeUtilities.checkNotNull(database, "database");
this.collection = database.getCollection(COLLECTION_PROPERTIES);
this.propertiesStore = new PropertiesResourceStore();
collection.createIndex(Indexes.ascending(USER_ID), new IndexOptions().unique(true));
}
public DescriptorStore(MongoDatabase database, IPermissionStore permissionStore, IUserStore userStore,
IGroupStore groupStore, IDocumentBuilder documentBuilder, Class<T> documentType) {
RuntimeUtilities.checkNotNull(database, "database");
RuntimeUtilities.checkNotNull(permissionStore, "permissionStore");
MongoCollection<Document> descriptorCollection = database.getCollection(COLLECTION_DESCRIPTORS);
MongoResourceStorage<T> resourceStorage =
new MongoResourceStorage<>(database, collectionName, documentBuilder, documentType);
this.descriptorResourceStore = new ModifiableHistorizedResourceStore<>(resourceStorage);
this.resourceFilter = new ResourceFilter<>(descriptorCollection, descriptorResourceStore,
permissionStore, userStore, groupStore, documentBuilder, documentType);
descriptorCollection.createIndex(Indexes.ascending(FIELD_RESOURCE), new IndexOptions().unique(true));
}
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);
}
}
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 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));
}
}
@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);
}