public IndexDefinition(
     IndexKeysDefinition <TDocument> keys,
     CreateIndexDefinitionOptions <TDocument> options)
 {
     Model = new CreateIndexModel <TDocument>(keys, options);
     IndexOptionsConflictResolution = options.IndexOptionsConflictResolution;
 }
Example #2
0
        /// <summary>
        /// Create unique index
        /// </summary>
        /// <param name="context">work context</param>
        /// <param name="collectionIndex">collection index information</param>
        /// <returns>Task</returns>
        public async Task CreateIndex(IWorkContext context, CollectionIndex collectionIndex)
        {
            Verify.IsNotNull(nameof(context), context);
            Verify.IsNotNull(nameof(collectionIndex), collectionIndex);
            Verify.IsNotEmpty(nameof(collectionIndex.Name), collectionIndex.Name);
            Verify.Assert(collectionIndex.Sparse == false || (collectionIndex?.Keys?.Count() == 0), "sparse index does not support compound indexes");
            Verify.Assert(collectionIndex.Keys?.Count > 0, "requires key definitions");
            context = context.WithTag(_tag);

            var options = new CreateIndexOptions
            {
                Name    = collectionIndex.Name,
                Version = 1,
                Unique  = collectionIndex.Unique,
                Sparse  = collectionIndex.Sparse,
            };

            IndexKeysDefinition <TDocument> keys = null;

            foreach (var key in collectionIndex.Keys)
            {
                if (key.Descending)
                {
                    keys = keys?.Descending(key.FieldName) ?? Builders <TDocument> .IndexKeys.Descending(key.FieldName);
                }
                else
                {
                    keys = keys?.Ascending(key.FieldName) ?? Builders <TDocument> .IndexKeys.Ascending(key.FieldName);
                }
            }

            MongoDbEventSource.Log.Info(context, $"Creating index={collectionIndex.Name}");
            await Parent.MongoCollection.Indexes.CreateOneAsync(keys, options, context.CancellationToken);
        }
Example #3
0
 private void CreateUniqueIndex <T>(IMongoCollection <T> collection, IndexKeysDefinition <T> definition)
 {
     collection.Indexes.CreateOne(new CreateIndexModel <T>(definition, new CreateIndexOptions
     {
         Unique = true
     }));
 }
        public void CreateUserLoginsIndex()
        {
            IndexKeysDefinition <MongoDbUserLogin> userIdIndex = Builders <MongoDbUserLogin> .IndexKeys
                                                                 .Ascending(p => p.UserId);

            CreateIndexOptions userIdOptions = new CreateIndexOptions()
            {
                Name   = "UserId",
                Unique = false
            };

            IndexKeysDefinition <MongoDbUserLogin> providerIndex = Builders <MongoDbUserLogin> .IndexKeys
                                                                   .Ascending(p => p.LoginProvider)
                                                                   .Ascending(p => p.ProviderKey);

            CreateIndexOptions providerOptions = new CreateIndexOptions()
            {
                Name   = "LoginProvider + ProviderKey",
                Unique = true
            };

            IMongoCollection <MongoDbUserLogin> collection = Context.UserLogins;

            collection.Indexes.DropAll();

            string loginIndexName    = collection.Indexes.CreateOne(userIdIndex, userIdOptions);
            string providerIndexName = collection.Indexes.CreateOne(providerIndex, providerOptions);
        }
        public void CreateUsersIndex()
        {
            IndexKeysDefinition <TUser> nameIndex = Builders <TUser> .IndexKeys
                                                    .Ascending(p => p.UserName);

            CreateIndexOptions nameOptions = new CreateIndexOptions()
            {
                Name   = "UserName",
                Unique = false
            };

            IndexKeysDefinition <TUser> emailIndex = Builders <TUser> .IndexKeys
                                                     .Ascending(p => p.Email);

            CreateIndexOptions emailOptions = new CreateIndexOptions()
            {
                Name   = "Email",
                Unique = false
            };

            IMongoCollection <TUser> collection = Context.Users;

            collection.Indexes.DropAll();

            string indexName  = collection.Indexes.CreateOne(nameIndex, nameOptions);
            string indexEmail = collection.Indexes.CreateOne(emailIndex, emailOptions);
        }
Example #6
0
        private void CreateIndex <TDoc>(IMongoCollection <TDoc> col, string[] indexFields, CreateIndexOptions options = null)
        {
            if (indexFields == null)
            {
                return;
            }
            var indexKeys = Builders <TDoc> .IndexKeys;
            IndexKeysDefinition <TDoc> keys = null;

            if (indexFields.Length > 0)
            {
                keys = indexKeys.Descending(indexFields[0]);
            }
            for (var i = 1; i < indexFields.Length; i++)
            {
                var strIndex = indexFields[i];
                keys = keys.Descending(strIndex);
            }

            if (keys != null)
            {
#pragma warning disable 618
                col?.Indexes?.CreateOne(keys, options);
#pragma warning restore 618
            }
        }
Example #7
0
        public void EnsureIndexExists()
        {
            string indexName = "instance_search";

            //I hate this loop. TODO: Find a better way to do this
            var  indexes     = this.Instances.Indexes.List().ToList();
            bool indexExists = false;

            foreach (var i in indexes)
            {
                if (i.ToString().Contains(indexName) == true)
                {
                    indexExists = true;
                }
            }

            if (indexExists == false)
            {
                IndexKeysDefinition <Dictionary <string, string> > keys = "{ FolderId:1, TypeId:1, '$**':'text' }";
                var indexModel = new CreateIndexModel <Dictionary <string, string> >(keys, new CreateIndexOptions()
                {
                    Name = indexName
                });
                this.Instances.Indexes.CreateOne(indexModel);
            }
        }
Example #8
0
        /// <summary>
        /// Verify the provided <paramref name="mongoIndex"/> is defined and ready to go.
        /// </summary>
        protected virtual void VerifyIndex(MongoDbIndex <MongoDbEventData> mongoIndex)
        {
            IndexKeysDefinitionBuilder <MongoDbEventData> indexKeysBuilder = Builders <MongoDbEventData> .IndexKeys;
            IndexKeysDefinition <MongoDbEventData>        indexKey         = null;

            IList <Expression <Func <MongoDbEventData, object> > > selectors = mongoIndex.Selectors.ToList();

            for (int i = 0; i < selectors.Count; i++)
            {
                Expression <Func <MongoDbEventData, object> > expression = selectors[i];
                if (mongoIndex.IsAcending)
                {
                    if (i == 0)
                    {
                        indexKey = indexKeysBuilder.Ascending(expression);
                    }
                    else
                    {
                        indexKey = indexKey.Ascending(expression);
                    }
                }
                else
                {
                    if (i == 0)
                    {
                        indexKey = indexKeysBuilder.Descending(expression);
                    }
                    else
                    {
                        indexKey = indexKey.Descending(expression);
                    }
                }
            }

            bool throwExceptions;

            if (!bool.TryParse(ConfigurationManager.GetSetting("Cqrs.MongoDb.EventStore.ThrowExceptionsOnIndexPreparation"), out throwExceptions))
            {
                throwExceptions = true;
            }
            try
            {
                MongoCollection.Indexes.CreateOne
                (
                    indexKey,
                    new CreateIndexOptions
                {
                    Unique = mongoIndex.IsUnique,
                    Name   = mongoIndex.Name
                }
                );
            }
            catch
            {
                if (throwExceptions)
                {
                    throw;
                }
            }
        }
Example #9
0
        public virtual void CreateSubscriberTopicSettingsIndex()
        {
            IndexKeysDefinition <SubscriberTopicSettings <ObjectId> > topicIndex = Builders <SubscriberTopicSettings <ObjectId> > .IndexKeys
                                                                                   .Ascending(p => p.CategoryId)
                                                                                   .Ascending(p => p.TopicId);

            CreateIndexOptions topicOptions = new CreateIndexOptions()
            {
                Unique = false
            };
            var topicModel = new CreateIndexModel <SubscriberTopicSettings <ObjectId> >(topicIndex, topicOptions);

            IndexKeysDefinition <SubscriberTopicSettings <ObjectId> > subscriberIndex = Builders <SubscriberTopicSettings <ObjectId> > .IndexKeys
                                                                                        .Ascending(p => p.SubscriberId);

            CreateIndexOptions subscriberOptions = new CreateIndexOptions()
            {
                Unique = false
            };
            var subscriberModel = new CreateIndexModel <SubscriberTopicSettings <ObjectId> >(subscriberIndex, subscriberOptions);


            IMongoCollection <SubscriberTopicSettings <ObjectId> > collection = _context.SubscriberTopicSettings;
            string topicName      = collection.Indexes.CreateOne(topicModel);
            string subscriberName = collection.Indexes.CreateOne(subscriberModel);
        }
Example #10
0
 public Task <string> CreateIndexAsync(IndexKeysDefinition <T> keys)
 {
     return(Retry(() =>
     {
         return Collection.Indexes.CreateOneAsync(new CreateIndexModel <T>(keys));
     }));
 }
Example #11
0
 public string CreateIndex(IndexKeysDefinition <T> keys)
 {
     return(Retry(() =>
     {
         return Collection.Indexes.CreateOne(new CreateIndexModel <T>(keys));
     }));
 }
Example #12
0
        public async Task CreateIndexIfNotExistsAsync <TDocument>(string collectionName, string indexName, int?ttl, params Expression <Func <TDocument, object> >[] fields)
        {
            var collection = CollectionMongo <TDocument>(collectionName);

            if (collection != null)
            {
                if (!await IndexExistsAsync(collection, indexName))
                {
                    IndexKeysDefinition <TDocument>[] indexKeys = new IndexKeysDefinition <TDocument> [fields.Length];

                    for (int i = 0; i < fields.Length; i++)
                    {
                        indexKeys[i] = Builders <TDocument> .IndexKeys.Ascending(fields[i]);
                    }

                    var indexDefinition = Builders <TDocument> .IndexKeys.Combine(indexKeys);

                    if (ttl.HasValue)
                    {
                        await collection.Indexes.CreateOneAsync(indexDefinition, new CreateIndexOptions { Name = indexName, ExpireAfter = TimeSpan.FromDays(ttl.Value) });
                    }
                    else
                    {
                        await collection.Indexes.CreateOneAsync(indexDefinition, new CreateIndexOptions { Name = indexName });
                    }
                }
            }
        }
        public MongoSettingsRepository(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Invalid mongo connection string");
            }

            try
            {
                var mongoUrl = MongoUrl.Create(connectionString);
                this.MongoClient        = new MongoClient(mongoUrl);
                this.Database           = this.MongoClient.GetDatabase(mongoUrl.DatabaseName);
                this.SettingsCollection = this.Database.GetCollection <SettingMongo>("Settings");
                // filters  and browsing by application and environment will be really common
                this.SettingsCollection.Indexes.CreateOne(Builders <SettingMongo> .IndexKeys.Ascending(s => s.Application));
                this.SettingsCollection.Indexes.CreateOne(Builders <SettingMongo> .IndexKeys.Ascending(s => s.Environment));
                // ensuring that there are no duplicated settings in a given app & env
                CreateIndexOptions indexOptions            = new CreateIndexOptions();
                IndexKeysDefinition <SettingMongo> keysDef = Builders <SettingMongo> .IndexKeys.Ascending(s => s.Application)
                                                             .Ascending(s => s.Environment)
                                                             .Ascending(s => s.Fullpath);

                indexOptions.Unique = true;
                this.SettingsCollection.Indexes.CreateOne(keysDef, indexOptions);
            }
            catch (Exception exp)
            {
                logger.Error("Expcetion when setting up Mongo Connection/DB/Collection for the settings4all", exp);
                throw;
            }
        }
        public static bool GenerateIndexes <T>(out IndexKeysDefinition <T> value)
            where T : BaseEntity
        {
            var properties = typeof(T).GetProperties();

            if (!properties.Any())
            {
                value = null;
                return(false);
            }
            else
            {
                value = Builders <T> .IndexKeys.Descending(x => x.Id);

                foreach (var property in properties)
                {
                    if (property.HasAttribute <BsonPropertyAttribute>(out var attr))
                    {
                        if (attr.BsonDirection == BsonDirection.DESC)
                        {
                            value = value.Descending(property.Name.ToRegular());
                        }
                        else if (attr.BsonDirection == BsonDirection.ASC)
                        {
                            value = value.Ascending(property.Name.ToRegular());
                        }
                    }
                }
                return(true);
            }
        }
Example #15
0
        private static BsonDocument Render <T>(this IndexKeysDefinition <T> definition)
        {
            var registry   = BsonSerializer.SerializerRegistry;
            var serializer = registry.GetSerializer <T>();

            return(definition.Render(serializer, registry));
        }
Example #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public async void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(option => option.EnableEndpointRouting = false)
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var config = new ServerConfig();

            Configuration.Bind(config);

            services.AddSingleton <IExerciseRepository, ExerciseRepository>();
            services.AddSingleton <IWorkoutServices, WorkoutServices.Services.WorkoutServices>();



            var mongoClient =
                new MongoClient(
                    config.MongoDB.ConnectionString);
            var db = mongoClient.GetDatabase("Workouts");

            services.AddSingleton(db);


            var options = new CreateIndexOptions()
            {
                Unique = true
            };
            IndexKeysDefinition <Exercise> keyField = "{ exerciseId: 1 }";
            await db.GetCollection <Exercise>("users").Indexes.CreateOneAsync(keyField, options);
        }
Example #17
0
        public void CreateIndex <T>(IMongoCollection <T> collection)
        {
            var typeProperties = typeof(T).GetProperties();

            foreach (var property in typeProperties)
            {
                IndexDescriptor indexDescriptor = property.GetCustomAttributes(typeof(IndexDescriptor), false).FirstOrDefault() as IndexDescriptor;

                if (indexDescriptor == null)
                {
                    continue;
                }

                IndexKeysDefinition <T> index = null;

                FieldDefinition <T> indexedColumn = property.Name;

                switch (indexDescriptor.Type)
                {
                case IndexType.Ascending:
                    index = new IndexKeysDefinitionBuilder <T>().Ascending(indexedColumn);
                    break;

                case IndexType.Descending:
                    index = new IndexKeysDefinitionBuilder <T>().Descending(indexedColumn);
                    break;

                case IndexType.Geo2D:
                    index = new IndexKeysDefinitionBuilder <T>().Geo2D(indexedColumn);
                    break;

                case IndexType.Geo2DSphere:
                    index = new IndexKeysDefinitionBuilder <T>().Geo2DSphere(indexedColumn);
                    break;

                case IndexType.Hashed:
                    index = new IndexKeysDefinitionBuilder <T>().Hashed(indexedColumn);
                    break;

                case IndexType.Text:
                    index = new IndexKeysDefinitionBuilder <T>().Text(indexedColumn);
                    break;

                default:
                    return;
                }

                if (index == null)
                {
                    return;
                }

                var indexModel = new CreateIndexModel <T>(index, new CreateIndexOptions()
                {
                    Background = indexDescriptor.Background, Sparse = indexDescriptor.Sparse, Unique = indexDescriptor.Unique
                });

                collection.Indexes.CreateOne(indexModel);
            }
        }
Example #18
0
        internal static void Init(IMongoDatabase database, string collectionName)
        {
            collection = database.GetCollection <T>(collectionName);

            // Apply custom modifiers
            foreach (PropertyInfo propInfo in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (propInfo.GetCustomAttribute <EnsureIndex>() is EnsureIndex indexAttribute)
                {
                    // Find the IndexDefinition based on the IndexType
                    IndexKeysDefinition <T> indexDef = null;
                    switch (indexAttribute.IndexType)
                    {
                    case IndexType.Ascending:
                        indexDef = Builders <T> .IndexKeys.Ascending(propInfo.Name);

                        break;

                    case IndexType.Descending:
                        indexDef = Builders <T> .IndexKeys.Descending(propInfo.Name);

                        break;
                    }

                    // Create the index
                    collection.Indexes.CreateOneAsync(new CreateIndexModel <T>(indexDef, new CreateIndexOptions()
                    {
                        Unique = indexAttribute.IsUnique
                    }));
                }
            }
        }
Example #19
0
 /// <summary>
 /// Create index for the collection
 /// </summary>
 /// <param name="keys">index definition</param>
 /// <param name="options">options</param>
 /// <returns>name of the index</returns>
 public virtual string CreateIndex(IndexKeysDefinition <T> keys, CreateIndexOptions options = null)
 {
     return(Retry(() =>
     {
         return Collection.Indexes.CreateOne(keys, options);
     }));
 }
        /// <summary>
        /// Creates an index, but ignore any error (it will only log them) to be used in projections.
        /// If a projections failed to create an index it will stop and this is not the best approach,
        /// we prefer to ignore indexing and log the error.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="keys"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public async Task CreateIndexAsync(String name, IndexKeysDefinition <TModel> keys, CreateIndexOptions options = null)
        {
            options      = options ?? new CreateIndexOptions();
            options.Name = name;

            //there is the possibility that create index trow if an index with same name and
            //different options/keys is created
            Boolean indexCreated = await InnerCreateIndexAsync(name, keys, options).ConfigureAwait(false);

            if (!indexCreated)
            {
                try
                {
                    //if we reach here, index was not created, probably it is existing and with different keys.
                    var indexExists = await _collection.IndexExistsAsync(name).ConfigureAwait(false);

                    if (indexExists)
                    {
                        await _collection.Indexes.DropOneAsync(name).ConfigureAwait(false);
                        await InnerCreateIndexAsync(name, keys, options).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat(ex, "Unable to create index {0}", name);
                }
            }
            else
            {
                Logger.ErrorFormat("Unable to create index {0}", name);
            }
        }
        public async Task <string> CreateIndex(Expression <Func <TEntity, object> > field)
        {
            IndexKeysDefinition <TEntity> keys = Builders <TEntity> .IndexKeys.Ascending(field);

            return(await _dbConnection.GetMongoDatabase.GetCollection <TEntity>(typeof(TEntity).Name)
                   .Indexes.CreateOneAsync(new CreateIndexModel <TEntity>(keys)));
        }
Example #22
0
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="keys"></param>
        public static void CreateOneIndexAsync <T>(IndexKeysDefinition <T> keys)
        {
            IMongoCollection <T> col = db.GetCollection <T>(typeof(T).Name);

            col.Indexes.DropAll();
            col.Indexes.CreateOneAsync(keys);
        }
Example #23
0
        static void CreateIndex()
        {
            IndexKeysDefinition <BsonDocument> keys = "{ Name: 1 }";
            var indexModel = new CreateIndexModel <BsonDocument>(keys);

            indexTest.Indexes.CreateOne(indexModel);
        }
        private void TryCreateIndex(IndexKeysDefinition <MessageJournalEntryDocument> indexKeys, string name = null)
        {
            var options = new CreateIndexOptions
            {
                Name = name
            };

            if (_collationSupported)
            {
                options.Collation = _collation;
            }

            try
            {
                _messageJournalEntries.Indexes.CreateOne(indexKeys, options);
                _diagnosticService.Emit(new MongoDBEventBuilder(this, MongoDBEventType.IndexCreated)
                {
                    DatabaseName   = _messageJournalEntries.Database.DatabaseNamespace.DatabaseName,
                    CollectionName = _messageJournalEntries.CollectionNamespace.CollectionName,
                    IndexName      = name ?? indexKeys.ToString()
                }.Build());
            }
            catch (Exception e)
            {
                _diagnosticService.Emit(new MongoDBEventBuilder(this, MongoDBEventType.IndexCreationFailed)
                {
                    DatabaseName   = _messageJournalEntries.Database.DatabaseNamespace.DatabaseName,
                    CollectionName = _messageJournalEntries.CollectionNamespace.CollectionName,
                    IndexName      = name ?? indexKeys.ToString(),
                    Exception      = e
                }.Build());
            }
        }
Example #25
0
        private CreateIndex(IndexKeysDefinition <TDto> definition, CreateIndexOptions options)
        {
            Precondition.For(definition, nameof(definition)).NotNull();

            Definition = definition;
            Options    = options;
        }
        static async Task createIndex(IMongoCollection <BsonDocument> collection)
        {
            //await collection.Indexes.CreateOneAsync(Builders<BsonDocument>.IndexKeys.Ascending(_ => _["quad"]));
            IndexKeysDefinition <BsonDocument> indexKey = Builders <BsonDocument> .IndexKeys.GeoHaystack("loc");

            //collection.Indexes.CreateOne(indexKey);
            await collection.Indexes.CreateOneAsync(indexKey);
        }
Example #27
0
        /// <inheritdoc />
        public virtual async Task Index(
            IndexKeysDefinition <TSchema> key,
            CreateIndexOptions <TSchema> options = null)
        {
            var model = new CreateIndexModel <TSchema>(key, options ?? new CreateIndexOptions());

            await this.Collection.Indexes.CreateOneAsync(model);
        }
Example #28
0
        private IMongoCollection <T> CreateOneAsync <T>(string collectionName, IndexKeysDefinition <T> keys, CreateIndexOptions options)
        {
            var collection = this.Database.GetCollection <T>(collectionName);

            //AsyncHelper.RunSync(() => collection.Indexes.CreateOneAsync(keys, options));

            return(collection);
        }
            public Task CreateIndex(string elementName)
            {
                IndexKeysDefinition <T> keys = Builders <T> .IndexKeys.Ascending(elementName);

                CreateIndexModel <T> index = new CreateIndexModel <T>(keys);

                return(Collection.Indexes.CreateOneAsync(index));
            }
Example #30
0
        public async void CreateIndexAsync <T>(IndexField index) where T : IBaseObject
        {
            this.CheckType <T>();
            IMongoCollection <T>    collection = this.GetCollection <T>();
            IndexKeysDefinition <T> keys       = (index.Direction == OrderDirection.ASC) ? Builders <T> .IndexKeys.Ascending(index.Field) : Builders <T> .IndexKeys.Descending(index.Field);

            await collection.Indexes.CreateOneAsync(keys, null, default(CancellationToken));
        }