Ejemplo n.º 1
0
        public static void EnsureUniqueIndexOnUserName(MongoCollection users)
        {
            var userName = new IndexKeysBuilder <IdentityUser>().Ascending(t => t.UserName);
            var unique   = new IndexOptionsBuilder().SetUnique(true);

            users.CreateIndex(userName, unique);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Initializes all the needed indexes for the pages to optimize search on them.
        /// </summary>
        public void InitializeIndexes()
        {
            // key options
            var options = new IndexOptionsBuilder().SetUnique(true);

            // page search key
            var keys = new IndexKeysBuilder().Ascending("Spot");

            Spots.EnsureIndex(keys, options);

            // general page search
            keys = new IndexKeysBuilder().Ascending("_id");
            Spots.EnsureIndex(keys, options);

            options.SetUnique(false);

            keys = new IndexKeysBuilder().Ascending("ParcelId");
            Spots.EnsureIndex(keys, options);

            keys = new IndexKeysBuilder().Ascending("CustomerId");
            Spots.EnsureIndex(keys, options);

            keys = new IndexKeysBuilder().Ascending("SponsorId");
            Spots.EnsureIndex(keys, options);
        }
Ejemplo n.º 3
0
        public static void EnsureUniqueIndexOnEmail(MongoCollection users)
        {
            var email  = new IndexKeysBuilder <IdentityUser>().Ascending(t => t.Email);
            var unique = new IndexOptionsBuilder().SetUnique(true);

            users.CreateIndex(email, unique);
        }
Ejemplo n.º 4
0
        public static void EnsureUniqueIndexOnRoleName(MongoCollection roles)
        {
            var roleName = new IndexKeysBuilder <IdentityRole>().Ascending(t => t.Name);
            var unique   = new IndexOptionsBuilder().SetUnique(true);

            roles.CreateIndex(roleName, unique);
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     添加索引
        /// </summary>
        /// <param name="IdxOpt"></param>
        /// <param name="option"></param>
        /// <param name="currentCollection"></param>
        /// <returns></returns>
        public static bool CreateMongoIndex(IndexOption IdxOpt,
                                            IndexOptionsBuilder option, MongoCollection currentCollection, ref string errorMessage)
        {
            var mongoCol  = currentCollection;
            var indexkeys = new IndexKeysBuilder();

            if (!string.IsNullOrEmpty(IdxOpt.GeoSpatialHaystackKey))
            {
                indexkeys.GeoSpatialHaystack(IdxOpt.GeoSpatialHaystackKey);
            }
            if (!string.IsNullOrEmpty(IdxOpt.GeoSpatialKey))
            {
                indexkeys.GeoSpatial(IdxOpt.GeoSpatialKey);
            }
            if (!string.IsNullOrEmpty(IdxOpt.GeoSpatialSphericalKey))
            {
                indexkeys.GeoSpatialSpherical(IdxOpt.GeoSpatialSphericalKey);
            }
            indexkeys.Ascending(IdxOpt.AscendingKey.ToArray());
            indexkeys.Descending(IdxOpt.DescendingKey.ToArray());
            indexkeys.Text(IdxOpt.TextKey.ToArray());
            //CreateIndex失败的时候会出现异常!
            try
            {
                var result = mongoCol.CreateIndex(indexkeys, option);
                return(result.Response.GetElement("ok").Value.AsInt32 == 1);
            }
            catch (Exception ex)
            {
                errorMessage = ex.ToString();
                return(false);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 增加索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdAddIndex_Click(object sender, EventArgs e)
        {
            List <String> AscendingKey  = new List <String>();
            List <String> DescendingKey = new List <String>();

            for (int i = 0; i < 5; i++)
            {
                ctlIndexCreate ctl = (ctlIndexCreate)Controls.Find("ctlIndexCreate" + (i + 1).ToString(), true)[0];
                if (ctl.KeyName != String.Empty)
                {
                    if (ctl.IsAscendingKey)
                    {
                        AscendingKey.Add(ctl.KeyName);
                    }
                    else
                    {
                        DescendingKey.Add(ctl.KeyName);
                    }
                }
            }
            IndexOptionsBuilder option = new IndexOptionsBuilder();

            option.SetBackground(chkIsBackground.Checked);
            option.SetDropDups(chkIsDroppedDups.Checked);
            option.SetSparse(chkIsSparse.Checked);
            option.SetUnique(chkIsUnique.Checked);
            if (txtIndexName.Text != String.Empty && !SystemManager.GetCurrentCollection().IndexExists(txtIndexName.Text))
            {
                option.SetName(txtIndexName.Text);
            }
            MongoDBHelper.CreateMongoIndex(AscendingKey.ToArray(), DescendingKey.ToArray(), option);
            RefreshList();
            MessageBox.Show("Index Add Completed!");
        }
Ejemplo n.º 7
0
        private void Init()
        {
            IndexKeysBuilder    keys        = IndexKeys.Ascending("metadata.directory_name");
            IndexOptionsBuilder options     = IndexOptions.SetName("directory_name").SetBackground(false);
            MongoGridFS         mongoGridFs = GetGridFS();

            mongoGridFs.EnsureIndexes();
            mongoGridFs.Files.EnsureIndex(keys, options);
        }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="_indexName"></param>
        /// <param name="_isUnique"></param>
        /// <param name="_isSparce"></param>
        /// <returns></returns>
        public static IMongoIndexOptions GetIndexOptions(string _indexName,
                                                         bool _isUnique, bool _isSparce = false)
        {
            IndexOptionsBuilder iob = new IndexOptionsBuilder();

            iob.SetName(_indexName);
            iob.SetUnique(_isUnique);
            iob.SetSparse(_isSparce);

            return(iob);
        }
        private void IndexExamples()
        {
            //insert
            IndexKeysBuilder <Car> carIndexBuilder = IndexKeys <Car> .Ascending(c => c.Make, c => c.NumberOfDoors);

            IndexOptionsBuilder <Car> carIndexOptions = IndexOptions <Car> .SetName("Car_CompositeIndex").SetTimeToLive(new TimeSpan(2, 0, 0, 0));

            CarRentalContext.Cars.EnsureIndex(carIndexBuilder, carIndexOptions);

            //delete
            CarRentalContext.Cars.DropIndexByName("Car_CompositeIndex");
        }
Ejemplo n.º 10
0
        protected override void OK()
        {
            var b = new IndexKeysBuilder();

            b.Ascending(SelectedField);
            var b1 = new IndexOptionsBuilder();

            b1.SetName(IndexName);
            _coll.CreateIndex(b, b1);

            ExistsIndexes = new ObservableCollection <IndexInfo>(GetExistsIndexes());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes all the needed indexes for the pages to optimize search on them.
        /// </summary>
        public void InitializeIndexes()
        {
            // key options
            var options = new IndexOptionsBuilder().SetUnique(true);

            // page search key
            var keys = new IndexKeysBuilder().Ascending("Role");

            Roles.EnsureIndex(keys, options);

            // general page search
            keys = new IndexKeysBuilder().Ascending("_id");
            Roles.EnsureIndex(keys, options);
        }
Ejemplo n.º 12
0
        private void CreateAdminIndexes()
        {
            var keys = new IndexKeysBuilder();

            keys.Ascending("DomainId", "ManagerId");

            var options = new IndexOptionsBuilder();

            options.SetSparse(true);
            options.SetUnique(true);

            var collection = _database.GetCollection <Administrator> ("administrators");

            collection.EnsureIndex(keys, options);
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     添加索引
        /// </summary>
        /// <param name="ascendingKey"></param>
        /// <param name="descendingKey"></param>
        /// <param name="geoSpatialKey"></param>
        /// <param name="option"></param>
        /// <param name="currentCollection"></param>
        /// <returns></returns>
        public static bool CreateMongoIndex(string[] ascendingKey, string[] descendingKey, string geoSpatialKey,
                                            IndexOptionsBuilder option, MongoCollection currentCollection)
        {
            var mongoCol  = currentCollection;
            var indexkeys = new IndexKeysBuilder();

            if (!string.IsNullOrEmpty(geoSpatialKey))
            {
                indexkeys.GeoSpatial(geoSpatialKey);
            }
            indexkeys.Ascending(ascendingKey);
            indexkeys.Descending(descendingKey);
            mongoCol.CreateIndex(indexkeys, option);
            return(true);
        }
        /// <summary>
        ///     添加索引
        /// </summary>
        /// <param name="AscendingKey"></param>
        /// <param name="DescendingKey"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static Boolean CreateMongoIndex(String[] AscendingKey, String[] DescendingKey, String GeoSpatialKey,
                                               IndexOptionsBuilder option)
        {
            MongoCollection mongoCol  = SystemManager.GetCurrentCollection();
            var             indexkeys = new IndexKeysBuilder();

            if (!String.IsNullOrEmpty(GeoSpatialKey))
            {
                indexkeys.GeoSpatial(GeoSpatialKey);
            }
            indexkeys.Ascending(AscendingKey);
            indexkeys.Descending(DescendingKey);
            mongoCol.CreateIndex(indexkeys, option);
            return(true);
        }
Ejemplo n.º 15
0
        private void CreateChangeRequestIndexes()
        {
            var keys = new IndexKeysBuilder();

            keys.Ascending("Id");

            var options = new IndexOptionsBuilder();

            options.SetSparse(true);
            options.SetUnique(true);

            var collection = database.GetCollection <CardChange>("card_changes");

            collection.EnsureIndex(keys, options);
        }
Ejemplo n.º 16
0
        private void CreateRoleIndexes()
        {
            var keys = new IndexKeysBuilder();

            keys.Ascending("Name", "DomainId");

            var options = new IndexOptionsBuilder();

            options.SetSparse(true);
            options.SetUnique(true);

            var collection = _database.GetCollection <Role> ("roles");

            collection.EnsureIndex(keys, options);
        }
Ejemplo n.º 17
0
        private void CreateUserCardIndexes()
        {
            var keys = new IndexKeysBuilder();

            keys.Ascending("PlaneswalkerId", "MultiverseId");

            var options = new IndexOptionsBuilder();

            options.SetSparse(true);
            options.SetUnique(true);

            var collection = database.GetCollection <UserCard>("user_cards");

            collection.EnsureIndex(keys, options);
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     设置Text索引
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="FieldName"></param>
        /// <param name="database"></param>
        public static void SetTextIndex(string collectionName, string FieldName, string database = "")
        {
            if (string.IsNullOrEmpty(database))
            {
                database = _defaultDatabaseName;
            }
            MongoCollection col = GetDatabaseByType(database).GetCollection(collectionName);

            if (col.IndexExistsByName(FieldName))
            {
                return;
            }
            var option = new IndexOptionsBuilder();

            option.SetName(FieldName);
            var indexkeys = new IndexKeysBuilder();

            indexkeys.Text(new string[] { FieldName });
            col.CreateIndex(indexkeys, option);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     设定数据缓存时间(以创建时间为基础)
        /// </summary>
        /// <param name="collectionName"></param>
        /// <param name="ExpiresMinute"></param>
        /// <param name="database"></param>
        public static void SetCacheTime(string collectionName, int ExpiresMinute, string database = "")
        {
            if (string.IsNullOrEmpty(database))
            {
                database = _defaultDatabaseName;
            }
            MongoCollection col = GetDatabaseByType(database).GetCollection(collectionName);

            if (col.IndexExistsByName("Cache"))
            {
                col.DropIndexByName("Cache");
            }
            var option = new IndexOptionsBuilder();

            option.SetTimeToLive(new TimeSpan(0, ExpiresMinute, 0));
            option.SetName("Cache");
            var indexkeys = new IndexKeysBuilder();

            indexkeys.Ascending(new string[] { nameof(EntityBase.CreateDateTime) });
            col.CreateIndex(indexkeys, option);
        }
        /// <summary>
        /// 添加索引
        /// </summary>
        /// <param name="AscendingKey"></param>
        /// <param name="DescendingKey"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static Boolean CreateMongoIndex(String[] AscendingKey, String[] DescendingKey, IndexOptionsBuilder option)
        {
            MongoCollection  mongoCol  = SystemManager.GetCurrentCollection();
            IndexKeysBuilder indexkeys = new IndexKeysBuilder();

            indexkeys.Ascending(AscendingKey);
            indexkeys.Descending(DescendingKey);
            mongoCol.CreateIndex(indexkeys, option);
            return(true);
        }
Ejemplo n.º 21
0
        public static bool CreateIndex(IndexOption UIOption, ref string strMessageTitle, ref string strMessageContent)
        {
            var Result = true;
            var option = new IndexOptionsBuilder();

            option.SetBackground(UIOption.IsBackground);
            option.SetDropDups(UIOption.IsDropDups);
            option.SetSparse(UIOption.IsSparse);
            option.SetUnique(UIOption.IsUnique);

            if (UIOption.IsExpireData)
            {
                //TTL的限制条件很多
                //http://docs.mongodb.org/manual/tutorial/expire-data/
                //不能是组合键
                var canUseTtl = true;
                if ((UIOption.ascendingKey.Count + UIOption.descendingKey.Count + (string.IsNullOrEmpty(UIOption.geoSpatialKey) ? 0 : 1)) != 1)
                {
                    strMessageTitle   = "Can't Set TTL";
                    strMessageContent = "the TTL index may not be compound (may not have multiple fields).";
                    canUseTtl         = false;
                }
                else
                {
                    //不能是_id
                    if (UIOption.firstKey == ConstMgr.KeyId)
                    {
                        strMessageTitle   = "Can't Set TTL";
                        strMessageContent = "you cannot create this index on the _id field, or a field that already has an index.";
                        canUseTtl         = false;
                    }
                }
                if (RuntimeMongoDbContext.GetCurrentCollection().IsCapped())
                {
                    strMessageTitle   = "Can't Set TTL";
                    strMessageContent = "you cannot use a TTL index on a capped collection, because MongoDB cannot remove documents from a capped collection.";
                    canUseTtl         = false;
                }
                if (canUseTtl)
                {
                    strMessageTitle   = "Constraints Of TimeToLive";
                    strMessageContent = "the indexed field must be a date BSON type. If the field does not have a date type, the data will not expire." +
                                        Environment.NewLine + "if the field holds an array, and there are multiple date-typed data in the index, the document will expire when the lowest (i.e. earliest) matches the expiration threshold.";
                    option.SetTimeToLive(new TimeSpan(0, 0, UIOption.TTL));
                }
            }
            var totalIndex = (UIOption.ascendingKey.Count + UIOption.descendingKey.Count +
                              (string.IsNullOrEmpty(UIOption.geoSpatialKey) ? 0 : 1) +
                              (string.IsNullOrEmpty(UIOption.textKey) ? 0 : 1));

            if (UIOption.IndexName != string.Empty && !RuntimeMongoDbContext.GetCurrentCollection().IndexExists(UIOption.IndexName) && totalIndex != 0)
            {
                option.SetName(UIOption.IndexName);
                try
                {
                    //暂时要求只能一个TextKey
                    if (!string.IsNullOrEmpty(UIOption.textKey))
                    {
                        var textKeysDoc = new IndexKeysDocument {
                            { UIOption.textKey, "text" }
                        };
                        RuntimeMongoDbContext.GetCurrentCollection().CreateIndex(textKeysDoc, option);
                    }
                    else
                    {
                        Operater.CreateMongoIndex(UIOption.ascendingKey.ToArray(), UIOption.descendingKey.ToArray(), UIOption.geoSpatialKey,
                                                  option, RuntimeMongoDbContext.GetCurrentCollection());
                    }
                    strMessageTitle   = "Index Add Completed!";
                    strMessageContent = "IndexName:" + UIOption.IndexName + " is add to collection.";
                }
                catch (Exception ex)
                {
                    strMessageTitle   = "Index Add Failed!";
                    strMessageContent = "IndexName:" + UIOption.IndexName;
                    Result            = false;
                }
            }
            else
            {
                strMessageTitle   = "Index Add Failed!";
                strMessageContent = "Please Check the index information.";
                Result            = false;
            }
            return(Result);
        }
 public static void EnsureUniqueIndexOnEmail(MongoCollection users)
 {
     var email = new IndexKeysBuilder<IdentityUser>().Ascending(t => t.Email);
     var unique = new IndexOptionsBuilder().SetUnique(true);
     users.CreateIndex(email, unique);
 }
 public static void EnsureUniqueIndexOnUserName(MongoCollection users)
 {
     var userName = new IndexKeysBuilder<IdentityUser>().Ascending(t => t.UserName);
     var unique = new IndexOptionsBuilder().SetUnique(true);
     users.CreateIndex(userName, unique);
 }
 public static void EnsureUniqueIndexOnRoleName(MongoCollection roles)
 {
     var roleName = new IndexKeysBuilder<IdentityRole>().Ascending(t => t.Name);
     var unique = new IndexOptionsBuilder().SetUnique(true);
     roles.CreateIndex(roleName, unique);
 }
Ejemplo n.º 25
0
        private void InvalidateRelationIndex(IStorageEntityRelation entityRelation)
        {
            MongoEntity originEntity = MongoStaticContext.Context.Entities.GetById(entityRelation.OriginEntityId);
            MongoEntity targetEntity = MongoStaticContext.Context.Entities.GetById(entityRelation.TargetEntityId);

            if (originEntity == null || targetEntity == null)
            {
                return;
            }

            IStorageField originField = originEntity.Fields.SingleOrDefault(x => x.Id == entityRelation.OriginFieldId);
            IStorageField targetField = targetEntity.Fields.SingleOrDefault(x => x.Id == entityRelation.TargetFieldId);

            if (originField == null || targetField == null)
            {
                return;
            }

            if (entityRelation.RelationType != Api.Models.EntityRelationType.ManyToMany)
            {
                var originCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + originEntity.Name);
                if (originCollection == null)
                {
                    return;
                }

                if (originField.Name != "id")
                {
                    var originIndexes   = originCollection.GetIndexes();
                    var originIndexName = "relation_" + entityRelation.Id + "_" + originField.Name;
                    var originIndex     = originIndexes.SingleOrDefault(x => x.Name == originIndexName);
                    if (originIndex != null)
                    {
                        originCollection.DropIndexByName(originIndexName);
                    }

                    IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(originIndexName).SetBackground(true);
                    originCollection.CreateIndex(new IndexKeysBuilder().Ascending(originField.Name), options);
                }

                var targetCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + targetEntity.Name);
                if (targetEntity == null)
                {
                    return;
                }

                if (targetField.Name != "id")
                {
                    var targetIndexes   = targetCollection.GetIndexes();
                    var targetIndexName = "relation_" + entityRelation.Id + "_" + targetField.Name;
                    var targetIndex     = targetIndexes.SingleOrDefault(x => x.Name == targetIndexName);
                    if (targetIndex != null)
                    {
                        targetCollection.DropIndexByName(targetIndexName);
                    }

                    IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(targetIndexName).SetBackground(true);
                    targetCollection.CreateIndex(new IndexKeysBuilder().Ascending(targetField.Name), options);
                }
            }
            else
            {
                var collection = MongoStaticContext.Context.GetBsonCollection(RELATION_COLLECTION_PREFIX + entityRelation.Name);

                var indexes         = collection.GetIndexes();
                var originIndexName = "relation_origin";
                var originIndex     = indexes.SingleOrDefault(x => x.Name == originIndexName);
                if (originIndex != null)
                {
                    collection.DropIndexByName(originIndexName);
                }

                IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(originIndexName).SetBackground(true);
                collection.CreateIndex(new IndexKeysBuilder().Ascending("relationId").Ascending("originId"), options);

                var targetIndexName = "relation_target";
                var targetIndex     = indexes.SingleOrDefault(x => x.Name == targetIndexName);
                if (targetIndex != null)
                {
                    collection.DropIndexByName(targetIndexName);
                }

                options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(targetIndexName).SetBackground(true);
                collection.CreateIndex(new IndexKeysBuilder().Ascending("relationId").Ascending("targetId"), options);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// </summary>
        /// <param name="KeyOptions"></param>
        /// <param name="strMessageTitle"></param>
        /// <param name="strMessageContent"></param>
        /// <returns></returns>
        public static bool CreateIndex(IndexOption KeyOptions, ref string strMessageTitle, ref string strMessageContent)
        {
            var option = new IndexOptionsBuilder();

            option.SetBackground(KeyOptions.IsBackground);
            option.SetDropDups(KeyOptions.IsDropDups);
            option.SetSparse(KeyOptions.IsSparse);
            option.SetUnique(KeyOptions.IsUnique);
            if (KeyOptions.IsPartial)
            {
                IMongoQuery query = (QueryDocument)BsonDocument.Parse(KeyOptions.PartialCondition);
                option.SetPartialFilterExpression(query);
            }
            if (KeyOptions.IsExpireData)
            {
                //TTL的限制条件很多
                //http://docs.mongodb.org/manual/tutorial/expire-data/
                //不能是组合键
                var canUseTtl = true;
                if (KeyOptions.AscendingKey.Count + KeyOptions.DescendingKey.Count +
                    (string.IsNullOrEmpty(KeyOptions.GeoSpatialKey) ? 0 : 1) != 1)
                {
                    strMessageTitle   = "Can't Set TTL";
                    strMessageContent = "the TTL index may not be compound (may not have multiple fields).";
                    canUseTtl         = false;
                }
                else
                {
                    //不能是_id
                    if (KeyOptions.FirstKey == ConstMgr.KeyId)
                    {
                        strMessageTitle   = "Can't Set TTL";
                        strMessageContent =
                            "you cannot create this index on the _id field, or a field that already has an index.";
                        canUseTtl = false;
                    }
                }
                if (RuntimeMongoDbContext.GetCurrentCollection().IsCapped())
                {
                    strMessageTitle   = "Can't Set TTL";
                    strMessageContent =
                        "you cannot use a TTL index on a capped collection, because MongoDB cannot remove documents from a capped collection.";
                    canUseTtl = false;
                }
                if (canUseTtl)
                {
                    strMessageTitle   = "Constraints Of TimeToLive";
                    strMessageContent =
                        "the indexed field must be a date BSON type. If the field does not have a date type, the data will not expire." +
                        Environment.NewLine +
                        "if the field holds an array, and there are multiple date-typed data in the index, the document will expire when the lowest (i.e. earliest) matches the expiration threshold.";
                    option.SetTimeToLive(new TimeSpan(0, 0, KeyOptions.Ttl));
                }
            }
            var totalIndex = KeyOptions.AscendingKey.Count + KeyOptions.DescendingKey.Count + KeyOptions.TextKey.Count;

            totalIndex += string.IsNullOrEmpty(KeyOptions.GeoSpatialHaystackKey) ? 0 : 1;
            totalIndex += string.IsNullOrEmpty(KeyOptions.GeoSpatialKey) ? 0 : 1;
            totalIndex += string.IsNullOrEmpty(KeyOptions.GeoSpatialSphericalKey) ? 0 : 1;

            if (string.IsNullOrEmpty(KeyOptions.IndexName) || totalIndex == 0 ||
                RuntimeMongoDbContext.GetCurrentCollection().IndexExists(KeyOptions.IndexName))
            {
                strMessageTitle   = "Index Add Failed!";
                strMessageContent = "Please Check the index information.";
                return(false);
            }
            option.SetName(KeyOptions.IndexName);
            string errorMessage = string.Empty;

            if (CreateMongoIndex(KeyOptions, option, RuntimeMongoDbContext.GetCurrentCollection(), ref errorMessage))
            {
                strMessageTitle   = "Index Add Completed!";
                strMessageContent = "IndexName:" + KeyOptions.IndexName + " is add to collection.";
                return(true);
            }
            else
            {
                strMessageTitle   = "Index Add Failed!";
                strMessageContent = errorMessage;
                return(false);
            }
        }
        private void InvalidateRelationIndex(IStorageEntityRelation entityRelation, bool dropIndexes = false)
        {
            var entityRepository = new MongoEntityRepository();

            var originEntity = entityRepository.Read(entityRelation.OriginEntityId);
            var targetEntity = entityRepository.Read(entityRelation.TargetEntityId);

            if (originEntity == null || targetEntity == null)
            {
                return;
            }

            IStorageField originField = originEntity.Fields.SingleOrDefault(x => x.Id == entityRelation.OriginFieldId);
            IStorageField targetField = targetEntity.Fields.SingleOrDefault(x => x.Id == entityRelation.TargetFieldId);

            if (originField == null || targetField == null)
            {
                return;
            }

            if (entityRelation.RelationType != Api.Models.EntityRelationType.ManyToMany)
            {
                var originCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + originEntity.Name);
                if (originCollection == null)
                {
                    return;
                }

                if (originField.Name != "id")
                {
                    var originIndexes   = originCollection.GetIndexes();
                    var originIndexName = "relation_" + entityRelation.Name + "_" + originField.Name;
                    var originIndex     = originIndexes.SingleOrDefault(x => x.Name == originIndexName);
                    if (originIndex != null)
                    {
                        originCollection.DropIndexByName(originIndexName);
                    }

                    if (!dropIndexes)
                    {
                        IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(originIndexName).SetBackground(true);
                        originCollection.CreateIndex(new IndexKeysBuilder().Ascending(originField.Name), options);
                    }
                }

                var targetCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + targetEntity.Name);
                if (targetEntity == null)
                {
                    return;
                }

                if (targetField.Name != "id")
                {
                    var targetIndexes   = targetCollection.GetIndexes();
                    var targetIndexName = "relation_" + entityRelation.Name + "_" + targetField.Name;
                    var targetIndex     = targetIndexes.SingleOrDefault(x => x.Name == targetIndexName);
                    if (targetIndex != null)
                    {
                        targetCollection.DropIndexByName(targetIndexName);
                    }

                    if (!dropIndexes)
                    {
                        IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(targetIndexName).SetBackground(true);
                        targetCollection.CreateIndex(new IndexKeysBuilder().Ascending(targetField.Name), options);
                    }
                }
            }
            else
            {
                //at the moment many to many relation do not need any endexes

                /*
                 * var originCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + originEntity.Name);
                 * if (originCollection == null)
                 *      return;
                 *
                 * var originIndexes = originCollection.GetIndexes();
                 * var originIndexName = "relation_" + entityRelation.Name + "_targets";
                 * var originIndex = originIndexes.SingleOrDefault(x => x.Name == originIndexName);
                 * if (originIndex != null)
                 *      originCollection.DropIndexByName(originIndexName);
                 *
                 * if (!dropIndexes)
                 * {
                 *      var originFieldName = $"#" + entityRelation.Name + "_targets";
                 *      IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(originIndexName).SetBackground(true);
                 *      originCollection.CreateIndex(new IndexKeysBuilder().Ascending(originFieldName), options);
                 * }
                 *
                 * var targetCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + targetEntity.Name);
                 * if (targetEntity == null)
                 *      return;
                 *
                 * var targetIndexes = targetCollection.GetIndexes();
                 * var targetIndexName = "relation_" + entityRelation.Name + "_origins";
                 * var targetIndex = targetIndexes.SingleOrDefault(x => x.Name == targetIndexName);
                 * if (targetIndex != null)
                 *      targetCollection.DropIndexByName(targetIndexName);
                 *
                 * if (!dropIndexes)
                 * {
                 *      var targetFieldName = $"#" + entityRelation.Name + "_origins";
                 *      IndexOptionsBuilder options = IndexOptions.SetUnique(false).SetDropDups(false).SetName(targetIndexName).SetBackground(true);
                 *      targetCollection.CreateIndex(new IndexKeysBuilder().Ascending(targetFieldName), options);
                 * }
                 */
            }
        }
        public void ConvertNtoNRelations()
        {
            List <IStorageEntityRelation> relations = Read();


            foreach (var relation in relations)
            {
                if (relation.RelationType != Api.Models.EntityRelationType.ManyToMany)
                {
                    continue;
                }

                MongoEntity   originEntity = MongoStaticContext.Context.Entities.GetById(relation.OriginEntityId);
                MongoEntity   targetEntity = MongoStaticContext.Context.Entities.GetById(relation.TargetEntityId);
                IStorageField originField  = originEntity.Fields.SingleOrDefault(x => x.Id == relation.OriginFieldId);
                IStorageField targetField  = targetEntity.Fields.SingleOrDefault(x => x.Id == relation.TargetFieldId);

                string originRelationFieldName = $"#{relation.Name}_origins";
                string targetRelationFieldName = $"#{relation.Name}_targets";

                var relationEntityRecordCollections = MongoStaticContext.Context.GetBsonCollection(RELATION_COLLECTION_PREFIX + relation.Name);
                var relationEntityRecords           = relationEntityRecordCollections.FindAll().ToList();

                if (relationEntityRecords != null && relationEntityRecords.Count() > 0)
                {
                    var transaction = MongoStaticContext.Context.CreateTransaction();

                    try
                    {
                        var originEntityRecordCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + originEntity.Name);
                        var originEntityRecords          = originEntityRecordCollection.FindAll().ToList();

                        if (originEntityRecords != null && originEntityRecords.Count() > 0)
                        {
                            foreach (var originRecord in originEntityRecords)
                            {
                                string      originFieldName     = originField.Name == "id" ? $"_id" : originField.Name;
                                List <Guid> targetRecordsToCopy = relationEntityRecords.Where(r => (Guid)r["originId"] == (Guid)originRecord[originFieldName]).Select(r => (Guid)r["targetId"]).ToList();

                                originRecord[targetRelationFieldName] = targetRecordsToCopy == null || targetRecordsToCopy.Count() == 0 ? BsonNull.Value : BsonValue.Create(targetRecordsToCopy);
                                var updateSuccess = originEntityRecordCollection.Save(originRecord).DocumentsAffected > 0;
                                //if (!updateSuccess)
                                //	throw new StorageException("Failed to update record.");
                            }
                        }

                        var targetEntityRecordCollection = MongoStaticContext.Context.GetBsonCollection(MongoRecordRepository.RECORD_COLLECTION_PREFIX + targetEntity.Name);
                        var targetEntityRecords          = targetEntityRecordCollection.FindAll().ToList();

                        if (targetEntityRecords != null && targetEntityRecords.Count() > 0)
                        {
                            foreach (var targetRecord in targetEntityRecords)
                            {
                                string      targetFieldName     = targetField.Name == "id" ? $"_id" : targetField.Name;
                                List <Guid> originRecordsToCopy = relationEntityRecords.Where(r => (Guid)r["targetId"] == (Guid)targetRecord[targetFieldName]).Select(r => (Guid)r["originId"]).ToList();

                                targetRecord[originRelationFieldName] = originRecordsToCopy == null || originRecordsToCopy.Count() == 0 ? BsonNull.Value : BsonValue.Create(originRecordsToCopy);;
                                var updateSuccess = targetEntityRecordCollection.Save(targetRecord).DocumentsAffected > 0;
                                //if (!updateSuccess)
                                //	throw new StorageException("Failed to update record.");
                            }
                        }

                        transaction.Commit();

                        IndexOptionsBuilder originOptions = IndexOptions.SetUnique(false).SetDropDups(false).SetName(targetRelationFieldName).SetBackground(true);
                        originEntityRecordCollection.CreateIndex(new IndexKeysBuilder().Ascending(targetRelationFieldName), originOptions);

                        IndexOptionsBuilder targetOptions = IndexOptions.SetUnique(false).SetDropDups(false).SetName(originRelationFieldName).SetBackground(true);
                        targetEntityRecordCollection.CreateIndex(new IndexKeysBuilder().Ascending(originRelationFieldName), targetOptions);
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                    }
                }
            }
        }
        /// <summary>
        ///     增加索引
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdAddIndex_Click(object sender, EventArgs e)
        {
            var    AscendingKey  = new List <String>();
            var    DescendingKey = new List <String>();
            String GeoSpatialKey = string.Empty;
            String FirstKey      = string.Empty;
            String TextKey       = String.Empty;

            for (int i = 0; i < 5; i++)
            {
                var ctl = (ctlIndexCreate)Controls.Find("ctlIndexCreate" + (i + 1), true)[0];
                if (ctl.KeyName == String.Empty)
                {
                    continue;
                }
                FirstKey = ctl.KeyName.Trim();
                switch (ctl.IndexKeyType)
                {
                case MongoDbHelper.IndexType.Ascending:
                    AscendingKey.Add(ctl.KeyName.Trim());
                    break;

                case MongoDbHelper.IndexType.Descending:
                    DescendingKey.Add(ctl.KeyName.Trim());
                    break;

                case MongoDbHelper.IndexType.GeoSpatial:
                    GeoSpatialKey = ctl.KeyName.Trim();
                    break;

                case MongoDbHelper.IndexType.Text:
                    TextKey = ctl.KeyName.Trim();
                    break;

                default:
                    break;
                }
            }
            var option = new IndexOptionsBuilder();

            option.SetBackground(chkIsBackground.Checked);
            option.SetDropDups(chkIsDroppedDups.Checked);
            option.SetSparse(chkIsSparse.Checked);
            option.SetUnique(chkIsUnique.Checked);
            if (chkExpireData.Checked)
            {
                //TTL的限制条件很多
                //http://docs.mongodb.org/manual/tutorial/expire-data/
                //不能是组合键
                Boolean CanUseTTL = true;
                if ((AscendingKey.Count + DescendingKey.Count + (String.IsNullOrEmpty(GeoSpatialKey) ? 0 : 1)) != 1)
                {
                    MyMessageBox.ShowMessage("Can't Set TTL",
                                             "the TTL index may not be compound (may not have multiple fields).");
                    CanUseTTL = false;
                }
                else
                {
                    //不能是_id
                    if (FirstKey == MongoDbHelper.KEY_ID)
                    {
                        MyMessageBox.ShowMessage("Can't Set TTL",
                                                 "you cannot create this index on the _id field, or a field that already has an index.");
                        CanUseTTL = false;
                    }
                }
                if (SystemManager.GetCurrentCollection().IsCapped())
                {
                    MyMessageBox.ShowMessage("Can't Set TTL",
                                             "you cannot use a TTL index on a capped collection, because MongoDB cannot remove documents from a capped collection.");
                    CanUseTTL = false;
                }
                if (CanUseTTL)
                {
                    MyMessageBox.ShowMessage("Constraints", "Constraints Of TimeToLive",
                                             "the indexed field must be a date BSON type. If the field does not have a date type, the data will not expire." +
                                             Environment.NewLine +
                                             "if the field holds an array, and there are multiple date-typed data in the index, the document will expire when the lowest (i.e. earliest) matches the expiration threshold.",
                                             true);
                    option.SetTimeToLive(new TimeSpan(0, 0, (int)numTTL.Value));
                }
            }
            if (txtIndexName.Text != String.Empty &&
                !SystemManager.GetCurrentCollection().IndexExists(txtIndexName.Text) &&
                (AscendingKey.Count + DescendingKey.Count +
                 (String.IsNullOrEmpty(GeoSpatialKey) ? 0 : 1) +
                 (String.IsNullOrEmpty(TextKey) ? 0 : 1)) != 0)
            {
                option.SetName(txtIndexName.Text);
                try
                {
                    //暂时要求只能一个TextKey
                    if (!string.IsNullOrEmpty(TextKey))
                    {
                        var TextKeysDoc = new IndexKeysDocument {
                            { TextKey, "text" }
                        };
                        SystemManager.GetCurrentCollection().CreateIndex(TextKeysDoc, option);
                    }
                    else
                    {
                        MongoDbHelper.CreateMongoIndex(AscendingKey.ToArray(), DescendingKey.ToArray(), GeoSpatialKey,
                                                       option);
                    }
                    MyMessageBox.ShowMessage("Index Add Completed!",
                                             "IndexName:" + txtIndexName.Text + " is add to collection.");
                }
                catch (Exception ex)
                {
                    SystemManager.ExceptionDeal(ex, "Index Add Failed!", "IndexName:" + txtIndexName.Text);
                }
                RefreshList();
            }
            else
            {
                MyMessageBox.ShowMessage("Index Add Failed!", "Please Check the index information.");
            }
        }
Ejemplo n.º 30
0
        private void CreateIndexBasicMode()
        {
            string indexName = txtBoxIndexName.Text;

            if (string.IsNullOrWhiteSpace(indexName))
            {
                throw new Exception("Please enter an index name.");
            }

            var mongoCollection = MongoCollectionInfo.GetMongoCollection();
            var indexes         = mongoCollection.GetIndexes();

            if (indexes != null && indexes.Any())
            {
                if (indexes.ToList().Exists(i => i.Name == indexName))
                {
                    throw new Exception("An index with that name already exists.");
                }
            }

            var keys = GetChoosenKeys();

            if (!keys.Any())
            {
                throw new Exception("You must choose at least one key.");
            }

            var keyBuilder = new IndexKeysBuilder();

            foreach (var key in keys)
            {
                if (key.SortType == 1)
                {
                    keyBuilder = keyBuilder.Ascending(key.Key);
                }
                else if (key.SortType == -1)
                {
                    keyBuilder = keyBuilder.Descending(key.Key);
                }
                else if (key.SortType == 2)
                {
                    keyBuilder = keyBuilder.GeoSpatial(key.Key);
                }
                else if (key.SortType == 3)
                {
                    keyBuilder = keyBuilder.GeoSpatialHaystack(key.Key);
                }
            }
            var optionBuilder = new IndexOptionsBuilder();

            optionBuilder.SetUnique(checkBoxUnique.Checked);
            optionBuilder.SetBackground(checkBoxBackground.Checked);
            optionBuilder.SetDropDups(checkBoxUnique.Checked && checkBoxDropDups.Checked);
            optionBuilder.SetSparse(checkBoxSparse.Checked);
            optionBuilder.SetName(indexName);

            var writeConcernResult = mongoCollection.CreateIndex(keyBuilder, optionBuilder);

            if (writeConcernResult.HasLastErrorMessage)
            {
                throw new Exception(writeConcernResult.LastErrorMessage);
            }
        }
Ejemplo n.º 31
0
        public void SetupCollection()
        {
            var           uri    = new MongoUrl(ConnectionString);
            var           client = new MongoClient(uri);
            MongoDatabase db     = client.GetServer().GetDatabase(uri.DatabaseName);
            Int64         cappedSize;

            if (!Int64.TryParse(CappedSizeInMb, out cappedSize))
            {
                cappedSize = 5 * 1024L;
            }
            if (!db.CollectionExists(CollectionName))
            {
                CollectionOptionsBuilder options = CollectionOptions
                                                   .SetCapped(true)
                                                   .SetMaxSize(1024L * 1024L * cappedSize); //5 gb.
                db.CreateCollection(CollectionName, options);
            }
            LogCollection = db.GetCollection(CollectionName);
            var builder = new IndexOptionsBuilder();

            const string ttlIndex = FieldNames.Timestamp + "_-1";
            var          index    = LogCollection.GetIndexes().SingleOrDefault(x => x.Name == ttlIndex);

            if (index != null)
            {
                if (ExpireAfter != null)
                {
                    if (index.TimeToLive != ExpireAfter.ToTimeSpan())
                    {
                        var d = new CommandDocument()
                        {
                            { "collMod", CollectionName },
                            {
                                "index", new BsonDocument
                                {
                                    { "keyPattern", new BsonDocument {
                                          { FieldNames.Timestamp, -1 }
                                      } },
                                    { "expireAfterSeconds", (int)(ExpireAfter.ToTimeSpan().TotalSeconds) }
                                }
                            }
                        };

                        db.RunCommand(d);
                    }
                }
            }
            else
            {
                if (ExpireAfter != null)
                {
                    builder.SetTimeToLive(ExpireAfter.ToTimeSpan());
                }

                LogCollection.CreateIndex(IndexKeys.Descending(FieldNames.Timestamp), builder);
            }

            LogCollection.CreateIndex(IndexKeys
                                      .Ascending(FieldNames.Level, FieldNames.Thread, FieldNames.Loggername)
                                      );
        }