Exemplo n.º 1
0
 public async Task CreateLocationIndex()
 {
     var builder    = Builders <User> .IndexKeys;
     var indexModel = new CreateIndexModel <User>(builder.Geo2DSphere(u => u.Location));
     await _database.GetCollection <User>(nameof(User)).Indexes
     .CreateOneAsync(indexModel);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Created index if not created
        /// </summary>
        /// <param name="connectionString">Connection string</param>
        /// <param name="database">Database</param>
        /// <returns></returns>
        public async Task Init(string connectionString, string database)
        {
            var client = new MongoClient(connectionString);
            var db     = client.GetDatabase(database);

            var roomsIndexKeyBuilder = Builders <Room> .IndexKeys;

            var compoundIndex = roomsIndexKeyBuilder.Ascending(x => x.RoomId).Ascending(x => x.PropertyId);
            var indexModel    = new CreateIndexModel <Room>(compoundIndex, new CreateIndexOptions()
            {
                Name = COMPOUND_INDEX, Background = true, Unique = true
            });

            var  existingIndexes  = await(await db.GetCollection <Room>("rooms").Indexes.ListAsync()).ToListAsync();
            bool hasCompoundIndex = false;

            foreach (var index in existingIndexes.Where(index => index.Values.Any(x => x.Equals(COMPOUND_INDEX))))
            {
                hasCompoundIndex = true;
            }

            if (!hasCompoundIndex)
            {
                await db.GetCollection <Room>("rooms").Indexes.CreateOneAsync(indexModel);
            }
        }
        public static void EnsureIndexes(MongoContext ctx)
        {
            var dateOrderIndex = new CreateIndexModel <EntranceLogEntry>(
                Builders <EntranceLogEntry> .IndexKeys.Descending(e => e.EntranceDate));

            ctx.EntranceLogEntries.Indexes.CreateOne(dateOrderIndex);
        }
Exemplo n.º 4
0
        public virtual void CreateSignalDispatchHistoryIndex(TimeSpan?historyExpirationTime)
        {
            var receiverIndex = Builders <SignalDispatch <ObjectId> > .IndexKeys
                                .Ascending(p => p.ReceiverSubscriberId)
                                .Ascending(p => p.SendDateUtc);

            var receiverOptions = new CreateIndexOptions()
            {
                Unique = false
            };
            var receiverModel = new CreateIndexModel <SignalDispatch <ObjectId> >(receiverIndex, receiverOptions);

            var ttlIndex = Builders <SignalDispatch <ObjectId> > .IndexKeys
                           .Ascending(p => p.CreateDateUtc);

            CreateIndexOptions ttlOptions = new CreateIndexOptions()
            {
                Name        = "CreateDateUtc TTL",
                Unique      = false,
                ExpireAfter = historyExpirationTime
            };
            var ttlModel = new CreateIndexModel <SignalDispatch <ObjectId> >(ttlIndex, ttlOptions);

            IMongoCollection <SignalDispatch <ObjectId> > collection = _context.SignalDispatchesHistory;
            string receiverName = collection.Indexes.CreateOne(receiverModel);

            if (historyExpirationTime != null)
            {
                string ttlName = collection.Indexes.CreateOne(ttlModel);
            }
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        public async Task CreateIndex()
        {
            var chunkIndexModel = new CreateIndexModel <Node>(Builders <Node> .IndexKeys.Ascending(x => x.Chunk));
            var idIndexModel    = new CreateIndexModel <Node>(Builders <Node> .IndexKeys.Ascending(x => x.OsmId));
            await _nodes.Indexes.CreateOneAsync(chunkIndexModel);

            await _nodes.Indexes.CreateOneAsync(idIndexModel);
        }
Exemplo n.º 7
0
        /// <inheritdoc/>
        public async Task <string> CreateOneIndexAsync(IndexKeysDefinition <T> keys, CreateIndexOptions options, CancellationToken cancellationToken = default)
        {
            var database     = client.GetDatabase(databaseName);
            var myCollection = database.GetCollection <T>(collectionName);
            var index        = new CreateIndexModel <T>(keys, options);

            return(await myCollection.Indexes.CreateOneAsync(index, cancellationToken : cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 8
0
        private void CreateIndex()
        {
            var indexKeys = Builders <MessageOutboxEntity> .IndexKeys.Ascending(message => message.IsProcessed);

            var indexModel = new CreateIndexModel <MessageOutboxEntity>(indexKeys);

            messages.Indexes.CreateOne(indexModel);
        }
Exemplo n.º 9
0
        protected override void EnsureIndexes()
        {
            var indexKeys = Builders <Topic> .IndexKeys.Ascending(_ => _.Name);

            var indexModel = new CreateIndexModel <Topic>(indexKeys);

            Collection.Indexes.CreateOneAsync(indexModel);
        }
Exemplo n.º 10
0
        /// <inheritdoc />
        public Task <string> EnsureIndexCreatedAsync()
        {
            var keys = Builders <Location> .IndexKeys.Geo2DSphere(z => z.Geometry);

            var model = new CreateIndexModel <Location>(keys);

            return(_collection.Indexes.CreateOneAsync(model));
        }
Exemplo n.º 11
0
 public static async Task CreateIndex <T>(this IMongoDatabase database,
                                          Func <IndexKeysDefinitionBuilder <T>, IndexKeysDefinition <T> > buildIndex)
 {
     var notificationLogBuilder = Builders <T> .IndexKeys;
     var collection             = database.GetCollection <T>(typeof(T).Name);
     var indexModel             = new CreateIndexModel <T>(buildIndex?.Invoke(notificationLogBuilder));
     await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
 }
Exemplo n.º 12
0
            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));
            }
Exemplo n.º 13
0
        /// <summary>
        /// MongoDB provides text indexes to support text search queries on string content.
        /// Text indexes can include any field whose value is a string or an array of string elements.
        /// </summary>
        public virtual void CreateIndex()
        {
            var filter = Builders <TEntity> .IndexKeys.Text("$**");

            var indexModel = new CreateIndexModel <TEntity>(filter);

            _collection.Indexes.CreateOne(indexModel);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        protected override void PreStart()
        {
            base.PreStart();

            _mongoDatabase = new Lazy <IMongoDatabase>(() =>
            {
                var connectionString = new MongoUrl(_settings.ConnectionString);
                var client           = new MongoClient(connectionString);

                return(client.GetDatabase(connectionString.DatabaseName));
            });

            _journalCollection = new Lazy <IMongoCollection <JournalEntry> >(() =>
            {
                var collection = _mongoDatabase.Value.GetCollection <JournalEntry>(_settings.Collection);

                if (_settings.AutoInitialize)
                {
                    var modelForEntryAndSequenceNr = new CreateIndexModel <JournalEntry>(Builders <JournalEntry>
                                                                                         .IndexKeys
                                                                                         .Ascending(entry => entry.PersistenceId)
                                                                                         .Descending(entry => entry.SequenceNr));

                    collection.Indexes
                    .CreateOneAsync(modelForEntryAndSequenceNr, cancellationToken: CancellationToken.None)
                    .Wait();

                    var modelWithOrdering = new CreateIndexModel <JournalEntry>(
                        Builders <JournalEntry>
                        .IndexKeys
                        .Ascending(entry => entry.Ordering));

                    collection.Indexes
                    .CreateOne(modelWithOrdering);
                }

                return(collection);
            });

            _metadataCollection = new Lazy <IMongoCollection <MetadataEntry> >(() =>
            {
                var collection = _mongoDatabase.Value.GetCollection <MetadataEntry>(_settings.MetadataCollection);

                if (_settings.AutoInitialize)
                {
                    var modelWithAscendingPersistenceId = new CreateIndexModel <MetadataEntry>(
                        Builders <MetadataEntry>
                        .IndexKeys
                        .Ascending(entry => entry.PersistenceId));

                    collection.Indexes
                    .CreateOneAsync(modelWithAscendingPersistenceId, cancellationToken: CancellationToken.None)
                    .Wait();
                }

                return(collection);
            });
        }
Exemplo n.º 16
0
        private void ConfigureIndexes()
        {
            IndexKeysDefinition <ProjectInfo> keys = Builders <ProjectInfo> .IndexKeys
                                                     .Text(x => x.ProjectName)
                                                     .Text(x => x.ProjectDescription)
                                                     .Text(x => x.AssemblyName)
                                                     .Text(x => x.ProjectUri)
                                                     .Text(x => x.Tags)
                                                     .Text($"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Name)}")
                                                     .Text($"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Description)}")
                                                     .Text($"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.DocumentationUri)}")
                                                     .Text($"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Tags)}")
            ;

            CreateIndexModel <ProjectInfo> indexModel = new CreateIndexModel <ProjectInfo>(keys, new CreateIndexOptions()
            {
                Weights = new BsonDocument(
                    new Dictionary <string, object>()
                {
                    //high priority
                    { nameof(ProjectInfo.ProjectName), 10 },
                    { nameof(ProjectInfo.AssemblyName), 10 },
                    { nameof(ProjectInfo.Tags), 10 },

                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Name)}", 10 },
                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Tags)}", 10 },

                    //medium priority
                    { nameof(ProjectInfo.ProjectDescription), 5 },
                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Description)}", 5 },
                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Properties)}.{nameof(Property.Value)}", 5 },
                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.Properties)}.{nameof(Property.ValueList)}", 5 },
                    { $"{nameof(ProjectInfo.Properties)}.{nameof(Property.Value)}", 5 },
                    { $"{nameof(ProjectInfo.Properties)}.{nameof(Property.ValueList)}", 5 },

                    //low priority
                    { nameof(ProjectInfo.ProjectUri), 3 },
                    { nameof(ProjectInfo.DocumentationUri), 3 },
                    { nameof(ProjectInfo.DownloadLocation), 3 },
                    { $"{nameof(ProjectInfo.Components)}.{nameof(ComponentManifest.DocumentationUri)}", 3 },
                }
                    )
            });

            this.projects.Indexes.CreateOne(indexModel);

            this.repositories.Indexes.CreateOne(
                new CreateIndexModel <RepositoryInfo>(
                    Builders <RepositoryInfo> .IndexKeys
                    .Ascending(r => r.OrganizationName)
                    .Ascending(r => r.RepositoryName), new CreateIndexOptions()
            {
                Sparse = true,
                Unique = true
            }
                    )
                );
        }
Exemplo n.º 17
0
        /// <summary>
        /// Find existing instance of ProcessManager
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mapper"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public IPersistanceData <T> FindData <T>(IProcessManagerPropertyMapper mapper, Message message) where T : class, IProcessManagerData
        {
            var mapping = mapper.Mappings.FirstOrDefault(m => m.MessageType == message.GetType()) ??
                          mapper.Mappings.First(m => m.MessageType == typeof(Message));

            var collectionName = typeof(T).Name;
            IMongoCollection <MongoDbSslData <T> > collection = _mongoDatabase.GetCollection <MongoDbSslData <T> >(collectionName);
            var indexOptions = new CreateIndexOptions();
            var indexKeys    = Builders <MongoDbSslData <T> > .IndexKeys.Ascending("Data.CorrelationId");

            var indexModel = new CreateIndexModel <MongoDbSslData <T> >(indexKeys, indexOptions);

            collection.Indexes.CreateOne(indexModel);

            object msgPropValue = null;

            try
            {
                msgPropValue = mapping.MessageProp.Invoke(message);
            }
            catch
            {
                return(null);
            }

            if (null == msgPropValue)
            {
                throw new ArgumentException("Message property expression evaluates to null");
            }

            //Left
            ParameterExpression pe   = Expression.Parameter(typeof(MongoDbSslData <T>), "t");
            Expression          left = Expression.Property(pe, typeof(MongoDbSslData <T>).GetTypeInfo().GetProperty("Data"));

            foreach (var prop in mapping.PropertiesHierarchy.Reverse())
            {
                left = Expression.Property(left, left.Type, prop.Key);
            }

            //Right
            Expression right = Expression.Constant(msgPropValue, msgPropValue.GetType());

            Expression expression;

            try
            {
                expression = Expression.Equal(left, right);
            }
            catch (InvalidOperationException ex)
            {
                throw new Exception("Mapped incompatible types of ProcessManager Data and Message properties.", ex);
            }

            Expression <Func <MongoDbSslData <T>, bool> > lambda = Expression.Lambda <Func <MongoDbSslData <T>, bool> >(expression, pe);

            return(collection.AsQueryable().FirstOrDefault(lambda));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Creates the index.
        /// </summary>
        private void CreateIndex()
        {
            var indexOptions = new CreateIndexOptions();
            var indexKeys    = Builders <Adviser> .IndexKeys.Ascending(adviser => adviser.UserDetails.Name);

            var indexModelName = new CreateIndexModel <Adviser>(indexKeys, indexOptions);

            DbSet.Indexes.CreateOne(indexModelName);
        }
Exemplo n.º 19
0
        public CommentContext(IOptions <Settings> settings)
        {
            var client = new MongoClient(settings.Value.ConnectionString);

            _database = client.GetDatabase(settings.Value.Database);
            var indexModel = new CreateIndexModel <PostComment>(Builders <PostComment> .IndexKeys.Ascending(c => c.PostId));

            PostComments.Indexes.CreateOne(indexModel);
        }
Exemplo n.º 20
0
        /*Build indexes on UserName field */
        public void BuildIndex()
        {
            System.Console.WriteLine("Building indexes - standby");
            var indexBuilder = Builders <TwitterData> .IndexKeys;
            var indexmodel   = new CreateIndexModel <TwitterData>(indexBuilder.Ascending(x => x.UserName));

            collection.Indexes.CreateOne(indexmodel);
            System.Console.WriteLine("Done building indexes");
        }
Exemplo n.º 21
0
        public async Task CreateIndexes()
        {
            //store id index
            var menuCollection = db.GetCollection <Menu>();
            var storeIdIndex   = Builders <Menu> .IndexKeys.Ascending(x => x.StoreId);

            var storeIdModel = new CreateIndexModel <Menu>(storeIdIndex);
            await menuCollection.Indexes.CreateOneAsync(storeIdModel);
        }
        static async Task SetIndexes()
        {
            var indexKeysDefinition = Builders <Location> .IndexKeys.Combine(
                Builders <Location> .IndexKeys.Ascending(x => x.VehicleId),
                Builders <Location> .IndexKeys.Ascending(x => x.UpdateDate));

            var indexModel = new CreateIndexModel <Location>(indexKeysDefinition);
            await context.Locations.Indexes.CreateOneAsync(indexModel);
        }
        /// <summary>
        /// Creates index on defined field.
        /// </summary>
        public async Task CreateIndexOnCollection(IMongoCollection <BsonDocument> collection, string field)
        {
            //var keys = Builders<BsonDocument>.IndexKeys.Ascending(field);
            //await collection.Indexes.CreateOneAsync(keys);

            var keys       = Builders <BsonDocument> .IndexKeys;
            var indexModel = new CreateIndexModel <BsonDocument>(keys.Ascending(field));
            await collection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
        }
        public static string CreateIndex <TDocument>(this IMongoCollection <TDocument> collection, Expression <Func <TDocument, object> > field)
        {
            var keys = Builders <TDocument> .IndexKeys.Ascending(field);

            var options = new CreateIndexOptions();
            var model   = new CreateIndexModel <TDocument>(keys, options);

            return(collection.Indexes.CreateOne(model));
        }
        /// <summary>
        /// Creates index on Name field.
        /// </summary>
        public async Task CreateIndexOnNameField()
        {
            //var keys = Builders<User>.IndexKeys.Ascending(x => x.Name);
            //await _usersCollection.Indexes.CreateOneAsync(keys).ConfigureAwait(false);

            var keys       = Builders <User> .IndexKeys;
            var indexModel = new CreateIndexModel <User>(keys.Ascending(x => x.Name));
            await _usersCollection.Indexes.CreateOneAsync(indexModel).ConfigureAwait(false);
        }
Exemplo n.º 26
0
        /// <summary>
        /// 添加索引
        /// </summary>
        public async Task AddIndex <T>(FieldDefinition <T> field)
        {
            var indexOptions = new CreateIndexOptions();
            var indexKeys    = Builders <T> .IndexKeys.Ascending(field);

            var indexModel = new CreateIndexModel <T>(indexKeys, indexOptions);

            await GetCollection <T>().Indexes.CreateOneAsync(indexModel);
        }
Exemplo n.º 27
0
        private static void EnsureExpireIndexOnTimeStamp(IMongoCollection <BsonDocument> collection, TimeSpan expireAfter)
        {
            var model = new CreateIndexModel <BsonDocument>(Builders <BsonDocument> .IndexKeys.Ascending(RequestProperties.TIMESTAMP_UTC),
                                                            new CreateIndexOptions {
                Background = true, ExpireAfter = expireAfter
            });

            collection.Indexes.CreateOneAsync(model);
        }
Exemplo n.º 28
0
        protected override Task PrepareAsync(CancellationToken ct = default)
        {
            var index =
                new CreateIndexModel <MongoContentEntity>(Index
                                                          .Ascending(x => x.ScheduledAt)
                                                          .Ascending(x => x.IsDeleted));

            return(Collection.Indexes.CreateOneAsync(index, cancellationToken: ct));
        }
Exemplo n.º 29
0
        public async Task EnsureIndex()
        {
            await _context.Posts.Indexes.DropAllAsync();

            var index = Builders <BlogPostModel> .IndexKeys.Text(x => x.Body);

            var indexModel = new CreateIndexModel <BlogPostModel>(index);
            await _context.Posts.Indexes.CreateOneAsync(indexModel);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates the lock indices
        /// </summary>
        /// <returns>Task</returns>
        public async Task CreateLockIndices()
        {
            IndexKeysDefinitionBuilder <LockEntry> lockIndexBuilder = Builders <LockEntry> .IndexKeys;
            CreateIndexModel <LockEntry>           categoryIndex    = new CreateIndexModel <LockEntry>(lockIndexBuilder.Ascending(x => x.Category));
            await _LockCollection.Indexes.CreateOneAsync(categoryIndex);

            CreateIndexModel <LockEntry> resourceIndex = new CreateIndexModel <LockEntry>(lockIndexBuilder.Ascending(x => x.ResourceId));
            await _LockCollection.Indexes.CreateOneAsync(resourceIndex);
        }
Exemplo n.º 31
0
        public static void EnsureJobIndexes(IMongoCollection<Job> jobCollection)
        {
            //Time Based indexes
            CreateIndexOptions<Job> options = new CreateIndexOptions<Job>();
            options.Background = true;

            List<CreateIndexModel<Job>> TimeIndexes = new List<CreateIndexModel<Job>>();

            var ascendCreateTime = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Ascending(x => x.CreateTime), options);
            TimeIndexes.Add(ascendCreateTime);

            var descendCreateTime = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Descending(x => x.CreateTime), options);
            TimeIndexes.Add(descendCreateTime);

            var ascendModifiedTime = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Ascending(x => x.ModifiedTime), options);
            TimeIndexes.Add(ascendModifiedTime);

            var descendModifiedTime = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Descending(x => x.ModifiedTime), options);
            TimeIndexes.Add(descendModifiedTime);

            jobCollection.Indexes.CreateMany(TimeIndexes);

            //JobState Index
            List<CreateIndexModel<Job>> BackgroundIndexes = new List<CreateIndexModel<Job>>();

            var ascendJobState = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Ascending(x=>x.State), options);
            BackgroundIndexes.Add(ascendCreateTime);
            var descendJobState = new CreateIndexModel<Job>(Builders<Job>.IndexKeys.Descending(x => x.State), options);
            BackgroundIndexes.Add(descendCreateTime);

            jobCollection.Indexes.CreateMany(BackgroundIndexes);

            //Geo Indexes
            var geoIndexOptions = new CreateIndexOptions();
            geoIndexOptions.Background = true;
            geoIndexOptions.Sparse = true;

            jobCollection.Indexes.CreateOne(Builders<Job>.IndexKeys.Geo2DSphere(x => x.Order.OrderLocation), geoIndexOptions);
        }