Beispiel #1
0
        private static void CreateIndex()
        {
            var exists = _client.IndexExists(Index);

            //基本配置
            IIndexState indexState = new IndexState()
            {
                Settings = new IndexSettings()
                {
                    NumberOfReplicas = 1, //副本数
                    NumberOfShards   = 5  //分片数
                }
            };

            if (!exists.Exists)
            {
                _client.CreateIndex(Index, p => p
                                    .InitializeUsing(indexState)
                                    .Mappings(ms =>
                                              ms.Map <Person>(m =>
                                                              m.AutoMap()
                                                              ))
                                    )

                ;
            }
        }
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <param name="esCreateIndexSettings">创建索引配置</param>
        /// <param name="mappingHandle">映射处理</param>
        internal static void CreateIndex(EsCreateIndexSettings esCreateIndexSettings, Action <ElasticClient, string> mappingHandle = null)
        {
            var aliasIndex     = esCreateIndexSettings.AliasIndex;
            var numberOfShards = esCreateIndexSettings.NumberOfShards;
            var index          = esCreateIndexSettings.Setting.EsDefaultIndex;
            var currClient     = GetClient(esCreateIndexSettings.Setting);

            if (string.IsNullOrEmpty(aliasIndex))
            {
                aliasIndex = esCreateIndexSettings.Setting.EsDefaultIndex;
            }
            //验证索引是否存在
            if (!currClient.Indices.Exists(index).Exists)
            {
                IIndexState indexState = new IndexState()
                {
                    Settings = new IndexSettings()
                    {
                        NumberOfReplicas = 0,
                        NumberOfShards   = numberOfShards
                    }
                };
                //按别名创建索引
                if (!string.IsNullOrEmpty(aliasIndex) && !aliasIndex.Equals(index))
                {
                    currClient.Indices.Create(index, c => c.InitializeUsing(indexState).Aliases(a => a.Alias(aliasIndex)));
                }
                else
                {
                    currClient.Indices.Create(index, c => c.InitializeUsing(indexState));
                }
            }
            mappingHandle?.Invoke(currClient, index);
        }
Beispiel #3
0
        public virtual async Task <IndexState> GetIndexStateAsync(string documentType)
        {
            var result = new IndexState {
                DocumentType = documentType, Provider = _connection.Provider, Scope = _connection.Scope
            };

            var searchRequest = new SearchRequest
            {
                Sorting = new[] { new SortingField {
                                      FieldName = KnownDocumentFields.IndexationDate, IsDescending = true
                                  } },
                Take = 1,
            };

            try
            {
                var searchResponse = await _searchProvider.SearchAsync(documentType, searchRequest);

                result.IndexedDocumentsCount = searchResponse.TotalCount;

                if (searchResponse.Documents?.Any() == true)
                {
                    var indexationDate = searchResponse.Documents[0].FirstOrDefault(kvp => kvp.Key.EqualsInvariant(KnownDocumentFields.IndexationDate));
                    result.LastIndexationDate = Convert.ToDateTime(indexationDate.Value);
                }
            }
            catch
            {
                // ignored
            }

            return(result);
        }
Beispiel #4
0
        public string Post([FromBody] Category category)
        {
            try
            {
                ElasticClient es = conn.Create();

                var settings = new IndexSettings {
                    NumberOfReplicas = 1, NumberOfShards = 2
                };

                var indexConfig = new IndexState
                {
                    Settings = settings
                };

                if (!es.IndexExists("categories").Exists)
                {
                    es.CreateIndex("categories", c => c
                                   .InitializeUsing(indexConfig)
                                   .Mappings(m => m.Map <Category>(mp => mp.AutoMap())));
                }

                esrepo.InsertDocument <Category>(es, category, "categories");
                return("Success");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        /// <summary>
        /// 创建索引,1个副本,5个分片
        /// 当索引存在的时候返回true
        /// 当索引不存在则创建,并根据T进行创建索引的mapping
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="indexName"></param>
        /// <returns></returns>
        private static bool CreateIndex <T>(string indexName) where T : class, new()
        {
            var response = client.IndexExists(indexName);

            if (!response.Exists)
            {
                IIndexState indexState = new IndexState()
                {
                    Settings = new IndexSettings()
                    {
                        NumberOfReplicas = 1, //副本数
                        NumberOfShards   = 5  //分片数
                    }
                };
                var indexResponse = client.CreateIndex(indexName, p => p.InitializeUsing(indexState).Mappings(x => x.Map <T>(y => y.AutoMap())));
                if (indexResponse.IsValid)
                {
                    return(true);
                }

                throw indexResponse.OriginalException;
            }

            return(true);
        }
Beispiel #6
0
        /// <summary>
        /// Prepare index
        /// </summary>
        /// <returns></returns>
        private static async Task GetData()
        {
            _state = IndexState.Downloading;

            String content = await DownloadFile(IndexUrl);

            //try to get previously downloaded file
            if (string.IsNullOrWhiteSpace(content))
            {
                if (File.Exists(TempFile))
                {
                    content = File.ReadAllText(TempFile);
                    _state  = IndexState.OkUsingCache;
                }
            }
            else
            {
                File.WriteAllText(TempFile, content);
            }

            ParseJson(content);

            if (!IsReady)
            {
                _state = IndexState.NoContent;
            }

            if (IsReady && _state != IndexState.OkUsingCache)
            {
                _state = IndexState.OK;
            }
        }
        public UsersElasticSearchRepository(IElasticClient client)
        {
            this.client = client;
            if (this.client.IndexExists("users").Exists)
            {
                return;
            }

            var indexSettings = new IndexSettings {
                NumberOfReplicas = 1, NumberOfShards = 2
            };

            var indexConfig = new IndexState
            {
                Settings = indexSettings
            };

            var response = this.client.CreateIndex(
                IndexName,
                c =>
                c.InitializeUsing(indexConfig)
                .Mappings(m => m.Map <UserIndex>(mp => mp.AutoMap())));

            if (response.IsValid)
            {
                Log.Information("Index Created. Data: {@data}", new
                {
                    Response   = response,
                    MethodName = "UsersElasticSearchRepository"
                });
            }
        }
Beispiel #8
0
        /// <summary>
        /// 创建索引
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="elasticClient"></param>
        /// <param name="indexName"></param>
        /// <param name="numberOfShards"></param>
        /// <param name="numberOfReplicas"></param>
        /// <returns></returns>
        public static bool CreateIndex <T>(this ElasticClient elasticClient, string indexName = "", int numberOfShards = 5, int numberOfReplicas = 1) where T : class
        {
            if (string.IsNullOrWhiteSpace(indexName))
            {
                indexName = typeof(T).Name;
            }

            if (elasticClient.Indices.Exists(indexName).Exists)
            {
                return(false);
            }
            else
            {
                var indexState = new IndexState()
                {
                    Settings = new IndexSettings()
                    {
                        NumberOfReplicas = numberOfReplicas,
                        NumberOfShards   = numberOfShards,
                    },
                };
                var response = elasticClient.Indices.Create(indexName, c => c.InitializeUsing(indexState).Map <T>(p => p.AutoMap()));
                return(response.Acknowledged);
            }
        }
Beispiel #9
0
        public void CreateIndexes()
        {
            var elasticClient = ESClient();

            var indexConfig = new IndexState
            {
                Settings = new IndexSettings {
                    NumberOfReplicas = 1, NumberOfShards = 2
                }
            };

            _indexes.ForEach(index =>
            {
                if (!elasticClient.IndexExists(index).Exists)
                {
                    switch (index)
                    {
                    case RequestMetrics.Name:
                        var response = elasticClient.CreateIndex(index, c => c
                                                                 .InitializeUsing(indexConfig)
                                                                 .Mappings(m => m.Map <RequestMetrics>(mp => mp.AutoMap())));
                        break;

                    case ApplicationMetrics.Name:
                        elasticClient.CreateIndex(index, c => c
                                                  .InitializeUsing(indexConfig)
                                                  .Mappings(m => m.Map <ApplicationMetrics>(mp => mp.AutoMap())));
                        break;
                    }
                }
            });
        }
        public ResultModel <bool> CreateIndex(TModel model, string indexName)
        {
            var result = new ResultModel <bool>();

            try
            {
                var settings = new IndexSettings {
                    NumberOfReplicas = 1, NumberOfShards = 3
                };

                var indexConfig = new IndexState
                {
                    Settings = settings
                };

                if (!EsClient.IndexExists(indexName).Exists)
                {
                    EsClient.CreateIndex(indexName, c => c
                                         .InitializeUsing(indexConfig)
                                         .Mappings(m => m.Map <TModel>(mp => mp.AutoMap())));
                }
                result.Value     = true;
                result.IsSuccess = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return(result);
        }
Beispiel #11
0
 public static bool CreateIndex(string indexName, int numberOfReplicas, int numberOfShards)
 {
     if (string.IsNullOrEmpty(indexName) || numberOfReplicas.Equals(0) || numberOfShards.Equals(0))
     {
         throw new ArgumentNullException("参数不能为空");
     }
     try
     {
         var         client     = GetClient();
         IIndexState indexState = new IndexState()
         {
             Settings = new IndexSettings()
             {
                 NumberOfReplicas = numberOfReplicas, //副本数
                 NumberOfShards   = numberOfShards    //分片数
             }
         };
         //创建索引 先不maping
         return(client.CreateIndex(indexName, p => p.InitializeUsing(indexState)).IsValid);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Beispiel #12
0
        public async Task SeedData()
        {
            try
            {
                var httpConnection = new AwsHttpConnection(new AwsSettings
                {
                    AccessKey = "AKIAI63FYLJHOUAV7HQA",
                    SecretKey = "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",
                    Region    = "us-east-1",
                });

                var           indexName = _config["ConnectionStrings:IndexName"];
                var           node      = new Uri("https://search-bunee-test-hxpcuz56nhqazfwlwz75wtexh4.us-east-1.es.amazonaws.com");
                var           pool      = new SingleNodeConnectionPool(node);
                var           settings  = new ConnectionSettings(pool, httpConnection).DefaultIndex(indexName);
                ElasticClient client    = new ElasticClient(settings);

                var result = client.TypeExists(indexName, typeof(Persona));
                if (!result.Exists)
                {
                    var indexSettings = new IndexSettings();
                    indexSettings.NumberOfReplicas = 1;
                    indexSettings.NumberOfShards   = 1;

                    var indexState = new IndexState();
                    indexState.Settings = indexSettings;

                    await client.CreateIndexAsync(indexName, f => f.InitializeUsing(indexState));
                }
            }
            catch
            {
                Console.WriteLine("Error al conectar a BD");
            }
        }
Beispiel #13
0
        /// <summary>
        /// 如果同名索引不存在则创建索引
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="client">ElasticClient实例</param>
        /// <param name="indexName">要创建的索引名称</param>
        /// <param name="numberOfReplicas">默认副本数量,如果是单实例,注意改成0</param>
        /// <param name="numberOfShards">默认分片数量</param>
        /// <returns></returns>
        public static bool CreateIndex <T>(this ElasticClient client, string indexName = "", int numberOfReplicas = 1, int numberOfShards = 5) where T : class
        {
            if (client.IndexExists(indexName).Exists)
            {
                return(false);
            }

            var indexState = new IndexState
            {
                Settings = new IndexSettings
                {
                    NumberOfReplicas = numberOfReplicas, //副本数
                    NumberOfShards   = numberOfShards    //分片数
                }
            };

            if (string.IsNullOrWhiteSpace(indexName))
            {
                indexName = typeof(T).Name.ToLower();
            }

            var result = client.CreateIndex(indexName, c => c.InitializeUsing(indexState).Mappings(ms => ms.Map <T>(m => m.AutoMap())));

            return(result.Acknowledged);
        }
Beispiel #14
0
        private IndexState CalculateIndex(IndexState lastIndex, IDictionary <string, decimal> topAssetsWeights,
                                          IDictionary <string, decimal> topUsingPrices)
        {
            if (lastIndex == null)
            {
                return(new IndexState(InitialIndexValue, topUsingPrices));
            }

            var signal = 0m;

            var topAssets = topAssetsWeights.Keys.ToList();

            foreach (var asset in topAssets)
            {
                var currentPrice  = topUsingPrices[asset];
                var previousPrice = Utils.GetPreviousMiddlePrice(asset, lastIndex, currentPrice);

                var weight = topAssetsWeights[asset];

                var r = currentPrice / previousPrice;

                signal += weight * r;
            }

            var indexValue = Math.Round(lastIndex.Value * signal, 2);

            var indexState = new IndexState(indexValue, topUsingPrices);

            return(indexState);
        }
 public void Read (TProtocol iprot)
 {
   bool isset_Status = false;
   TField field;
   iprot.ReadStructBegin();
   while (true)
   {
     field = iprot.ReadFieldBegin();
     if (field.Type == TType.Stop) { 
       break;
     }
     switch (field.ID)
     {
       case 1:
         if (field.Type == TType.I32) {
           Status = (IndexState)iprot.ReadI32();
           isset_Status = true;
         } else { 
           TProtocolUtil.Skip(iprot, field.Type);
         }
         break;
       default: 
         TProtocolUtil.Skip(iprot, field.Type);
         break;
     }
     iprot.ReadFieldEnd();
   }
   iprot.ReadStructEnd();
   if (!isset_Status)
     throw new TProtocolException(TProtocolException.INVALID_DATA);
 }
Beispiel #16
0
        public void CalculateState()
        {
            var defineList = index_definition_infos();

            //根据定义生成指数信息
            foreach (IndexDefinitionInfo define in defineList)
            {
                //计算状态数据
                IndexState stateResult = IndexState.Warn;
                try
                {
                    stateResult = CalculateState(define);
                }
                catch (Exception ex)
                {
                    this.Log().Error("计算技术状态异常:对象类型:{0},对象编码:{1},周期:{2},技术:{3},\r\n异常信息:{4}"
                                     .Format(this.ObjectType, this.ObjectCode, this.Cycle, define.name, ex.GetAllExptionMessage() + ex.StackTrace));
                }
                //存储状态
                try
                {
                    SaveTechState(define, stateResult);
                }
                catch (Exception ex)
                {
                    this.Log().Error("保存状态数据异常:对象类型:{0},对象编码:{1},周期:{2},技术:{3},\r\n异常信息:{4}"
                                     .Format(this.ObjectType, this.ObjectCode, this.Cycle, define.name, ex.GetAllExptionMessage() + ex.StackTrace));

                    //回滚
                    //ClearTechData(define);
                    continue;
                }
            }
        }
        /// <summary>
        /// 如果同名索引不存在则创建索引
        /// </summary>
        /// <param name="client">ElasticClient实例</param>
        /// <param name="indexName">要创建的索引名称</param>
        /// <param name="numberOfReplicas">默认副本数量,如果是单实例,注意改成0</param>
        /// <param name="numberOfShards">默认分片数量</param>
        /// <returns></returns>
        public static bool CreateIndex <T>(IElasticClient client, string indexName = "wizplant", int numberOfReplicas = 1, int numberOfShards = 5) where T : class
        {
            var existsResponse = client.Indices.Exists(indexName);

            // 存在则返回true 不存在创建
            if (existsResponse.Exists)
            {
                return(true);
            }
            var indexState = new IndexState
            {
                Settings = new IndexSettings
                {
                    NumberOfReplicas = numberOfReplicas, //副本数
                    NumberOfShards   = numberOfShards    //分片数
                }
            };

            if (string.IsNullOrWhiteSpace(indexName))
            {
                indexName = typeof(T).Name.ToLower();
            }
            CreateIndexResponse response = client.Indices.Create(indexName, p => p.InitializeUsing(indexState).Map <T>(r => r.AutoMap()));

            // var result = client.CreateIndex(indexName, c => c.InitializeUsing(indexState).Mappings(ms => ms.Map<T>(m => m.AutoMap())));
            return(response.IsValid);
        }
Beispiel #18
0
        /// <summary>
        /// 封装后的创建index
        /// </summary>
        /// <param name="indexName"></param>
        /// <param name="shards">分片数量,即数据块最小单元</param>
        /// <returns></returns>
        public async Task <bool> AddIndexAsync(string indexName, int shards = 5)
        {
            try {
                var isHaveIndex = await IsExsitIndex(indexName.ToLower());

                if (!isHaveIndex)
                {
                    var setting = new IndexState()
                    {
                        Settings = new IndexSettings()
                        {
                            NumberOfReplicas = 0,      //副本数
                            NumberOfShards   = shards, //分片数
                            RefreshInterval  = -1
                        }
                    };
                    var response = await Client.Indices
                                   .CreateAsync(indexName, x => x.InitializeUsing(setting)
                                                .Map <TEntity>(y => y.AutoMap()));

                    return(response.Acknowledged);
                }
            }
            catch (Exception ex) {
                throw;
            }
            return(true);
        }
        public static bool CreateIndex <T>(IElasticClient elasticClient, string indexName) where T : class
        {
            var existsResponse = elasticClient.Indices.Exists(indexName);

            // 存在则返回true 不存在创建
            if (existsResponse.Exists)
            {
                return(true);
            }
            //基本配置
            IIndexState indexState = new IndexState
            {
                Settings = new IndexSettings
                {
                    NumberOfReplicas = 1, // 副本数
                    NumberOfShards   = 6, // 分片数
                },
            };

            CreateIndexResponse response = elasticClient.Indices.Create(indexName, p => p
                                                                        .InitializeUsing(indexState).Map <T>(r => r.AutoMap())
                                                                        );

            return(response.IsValid);
        }
Beispiel #20
0
        /// <summary>
        /// Creates Index Async ps:if index doesnt exist
        /// </summary>
        /// <typeparam name="TClass">Class type</typeparam>
        /// <param name="indexName">index name</param>
        /// <param name="numberOfReplicas">replica count</param>
        /// <param name="numberOfShards">shard count </param>
        public static Task <ICreateIndexResponse> CreateIndexAsync <TClass>(string indexName, int numberOfReplicas, int numberOfShards) where TClass : class
        {
            var settings = new IndexSettings {
                NumberOfReplicas = numberOfReplicas, NumberOfShards = numberOfShards
            };

            var indexConfig = new IndexState
            {
                Settings = settings
            };

            if (!EsClient.IndexExists(indexName).Exists)
            {
                //EsClient.DeleteIndex("testindex");
                return(EsClient.CreateIndexAsync(indexName, c => c
                                                 .Mappings(ms => ms
                                                           .Map <TClass>(m => m
                                                                         .AutoMap(typeof(TClass))
                                                                         )
                                                           )
                                                 ));
            }
            else
            {
                return(null);
            }
        }
Beispiel #21
0
        //public static void CreateIndex()
        //{
        //    CreateIndex(defaultIndexName);
        //}

        public static void CreateIndex(ElasticClient client)
        {
            IndexSettings set = new IndexSettings();

            set.NumberOfReplicas = 2;
            set.NumberOfShards   = 25;

            // Add the Analyzer with a name
            set.Analysis = new Nest.Analysis()
            {
                Analyzers    = new Analyzers(),
                TokenFilters = BasicTokenFilters(),
            };

            set.Analysis.Analyzers.Add("default", DefaultAnalyzer());

            IndexState idxSt = new IndexState();

            idxSt.Settings = set;

            var res = client.Indices
                      .Create(client.ConnectionSettings.DefaultIndex, i => i
                              .InitializeUsing(idxSt)
                              .Map(mm => mm
                                   .Properties(ps => ps
                                               .Date(psn => psn.Name("DbCreated"))
                                               .Keyword(psn => psn.Name("DbCreatedBy"))
                                               )
                                   )

                              );
        }
        public static async Task CreateIndexAsync <T>(this ElasticClient elasticClient, string indexName = "", int numberOfShards = 5, int numberOfReplicas = 1) where T : class
        {
            if (string.IsNullOrWhiteSpace(indexName))
            {
                throw new ArgumentException("索引名称不可为空");
            }

            if (!(await elasticClient.Indices.ExistsAsync(indexName)).Exists)
            {
                var indexState = new IndexState
                {
                    Settings = new IndexSettings
                    {
                        NumberOfReplicas = numberOfReplicas,
                        NumberOfShards   = numberOfShards,

                        // index.blocks.read_only:设为true,则索引以及索引的元数据只可读
                        // index.blocks.read_only_allow_delete:设为true,只读时允许删除。
                        // index.blocks.read:设为true,则不可读。
                        // index.blocks.write:设为true,则不可写。
                        // index.blocks.metadata:设为true,则索引元数据不可读写
                    }
                };
                var response = await elasticClient.Indices.CreateAsync(indexName, p => p.InitializeUsing(indexState).Map <T>(x => x.AutoMap()));

                if (!response.IsValid)
                {
                    throw new Exception($"创建索引失败:{response.OriginalException.Message}");
                }
            }
        }
Beispiel #23
0
        public static async Task <bool> CreateIndex <T>(this ElasticClient client, string indexName = "", int numberOfShards = 5, int numberOfReplicas = 1) where T : class
        {
            if (indexName.IsNullOrWhiteSpace())
            {
                indexName = typeof(T).Name;
            }

            var existResponse = await client.Indices.ExistsAsync(indexName);

            if (existResponse.Exists)
            {
                return(false);
            }
            var idxState = new IndexState
            {
                Settings = new IndexSettings()
                {
                    NumberOfReplicas = numberOfReplicas,
                    NumberOfShards   = numberOfShards
                }
            };
            var response = await client.Indices.CreateAsync(indexName, x => x.InitializeUsing(idxState).Map <T>(i => i.AutoMap()));

            return(response.Acknowledged);
        }
Beispiel #24
0
        public ElasticAuditorProvider(ElasticSetting elasticSetting)
        {
            _elasticSetting = elasticSetting;

            _node     = new Uri(_elasticSetting.ConnectionString);
            _settings = new ConnectionSettings(_node);
            _client   = new ElasticClient(_settings);

            if (!string.IsNullOrEmpty(_elasticSetting.Username) && !string.IsNullOrEmpty(_elasticSetting.Password))
            {
                _settings.BasicAuthentication(_elasticSetting.Username, _elasticSetting.Password);
                _settings.ServerCertificateValidationCallback(
                    (o, certificate, arg3, arg4) => true);
            }

            var indexSettings = new IndexSettings {
                NumberOfReplicas = 1, NumberOfShards = 5
            };
            var indexConfig = new IndexState {
                Settings = indexSettings
            };

            ReformatIndex();

            _indexName = string.Format(_elasticSetting.IndexFormat, DateTime.Now.Date.ToString("yyyy.MM.dd"));

            if (!_client.IndexExists(_indexName).Exists)
            {
                _client.CreateIndex(_indexName, c => c
                                    .InitializeUsing(indexConfig)
                                    .Mappings(m => m.Map <Audit>(mp => mp.AutoMap(typeof(Audit)).AutoMap <Audit>())));
            }
        }
Beispiel #25
0
        public async Task InitAsync()
        {
            try
            {
                IIndexState indexState = new IndexState()
                {
                    Settings = new IndexSettings()
                    {
                        NumberOfReplicas = 1,
                        NumberOfShards   = 3
                    }
                };


                var RequestInfoIndex = await Client.Indices.ExistsAsync(GetIndexName <RequestInfo>());

                if (!RequestInfoIndex.Exists)
                {
                    await Client.Indices.CreateAsync(GetIndexName <RequestInfo>(), a => a.InitializeUsing(indexState));

                    await Client.MapAsync <Models.RequestInfo>(c => c.Index(GetIndexName <RequestInfo>()).AutoMap());
                }

                var MonitorJobIndex = await Client.Indices.ExistsAsync(GetIndexName <MonitorJob>());

                if (!MonitorJobIndex.Exists)
                {
                    await Client.Indices.CreateAsync(GetIndexName <MonitorJob>(), a => a.InitializeUsing(indexState));

                    await Client.MapAsync <Models.MonitorJob>(c => c.Index(GetIndexName <MonitorJob>()).AutoMap());
                }


                var SysUserIndex = await Client.Indices.ExistsAsync(GetIndexName <SysUser>());

                if (!SysUserIndex.Exists)
                {
                    await Client.Indices.CreateAsync(GetIndexName <SysUser>(), a => a.InitializeUsing(indexState));

                    await Client.MapAsync <Models.SysUser>(c => c.Index(GetIndexName <SysUser>()).AutoMap());
                }

                var user = await Client.SearchAsync <SysUser>(s => s.Index(GetIndexName <SysUser>()).Query(q => q.MatchAll())).ConfigureAwait(false);

                if (user.Documents.Count == 0)
                {
                    await Client.IndexAsync <SysUser>(new SysUser
                    {
                        Id       = MD5_16(Guid.NewGuid().ToString()),
                        UserName = Core.Config.BasicConfig.DefaultUserName,
                        Password = Core.Config.BasicConfig.DefaultPassword
                    }, x => x.Index(GetIndexName <SysUser>()));
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #26
0
        private void SaveTechState(IndexDefinitionInfo define, IndexState result)
        {
            using (StockManDBEntities entity = new StockManDBEntities())
            {
                var cate        = (int)this.ObjectType + "";
                var code        = cate + "_" + this.ObjectCode + "_" + define.code;
                var objectState = entity.objectstate.FirstOrDefault(p => p.code == code);
                if (objectState == null)
                {
                    var temp = new objectstate()
                    {
                        code          = code,
                        category_code = cate,
                        object_code   = this.ObjectCode,
                        index_code    = define.code,
                        date          = DateTime.Now
                    };

                    switch (this.Cycle)
                    {
                    case TechCycle.day:
                        temp.day = (int)result;
                        break;

                    case TechCycle.week:
                        temp.week = (int)result;
                        break;

                    default:
                        temp.month = (int)result;
                        break;
                    }
                    entity.objectstate.Add(temp);
                }
                else
                {
                    switch (this.Cycle)
                    {
                    case TechCycle.day:
                        objectState.last_day = objectState.day;
                        objectState.day      = (int)result;
                        break;

                    case TechCycle.week:
                        objectState.last_week = objectState.week;
                        objectState.week      = (int)result;
                        break;

                    default:
                        objectState.last_month = objectState.month;
                        objectState.month      = (int)result;
                        break;
                    }
                    objectState.date = DateTime.Now;
                }

                entity.SaveChanges();
            }
        }
Beispiel #27
0
        private async Task SaveAsync(IndexState indexState, IndexHistory indexHistory)
        {
            // Save index state for the next execution
            await _indexStateRepository.SetAsync(indexState);

            // Save index history
            await _indexHistoryRepository.InsertAsync(indexHistory);
        }
Beispiel #28
0
        static void Main(string[] args)
        {
            try
            {
                // Setting up the node of elastic server
                Node = new Uri("http://localhost:9200/");

                //Passing Node to connection settings ad also setting up the default index
                Settings = new ConnectionSettings(Node).DefaultIndex("my_newblog");

                // Finally setting up the client
                Client = new ElasticClient(Settings);

                // Setting up the number of replicas and shards
                var settings = new IndexSettings {
                    NumberOfReplicas = 1, NumberOfShards = 2
                };

                var indexConfig = new IndexState
                {
                    Settings = settings
                };

                // Creating Index if it does not exists
                if (!Client.IndexExists("my_newblog").Exists)
                {
                    Client.CreateIndex("my_newblog", c => c
                                       .InitializeUsing(indexConfig)
                                       .Mappings(m => m.Map <Post>(mp => mp.AutoMap())));
                }

                // The following lines are methods for various operations using elastic. Comment / Uncomment appropriately

                //InsertData();

                //foreach (var r in PerformTermQuery("blog")) {
                //    Console.WriteLine(r.PostText);
                //}

                //foreach (var r in PerformMatchPhrase("New post from NEST"))
                //{
                //    Console.WriteLine(r.PostText);
                //}


                foreach (var r in PerformTermFilterWithDateGt("blog", DateTime.Now))
                {
                    Console.WriteLine(r.PostText);
                }

                Console.ReadKey();
            }
            catch (Exception ex) {
                Console.Write(ex.Message);
                Console.ReadKey();
            }
        }
Beispiel #29
0
        public async Task SetAsync(IndexState indexState)
        {
            var model = Mapper.Map <IndexStateEntity>(indexState);

            model.PartitionKey = ConstKey;
            model.RowKey       = ConstKey;

            await _storage.InsertOrReplaceAsync(model);
        }
Beispiel #30
0
        private void CreateElasticIndex(Database db, ElasticClient client)
        {
            var ret = client.IndexExists(client.ConnectionSettings.DefaultIndex);

            if (!ret.Exists)
            {
                var set = new IndexSettings
                {
                    NumberOfReplicas = 2,
                    NumberOfShards   = 25
                };
                var an = new CustomAnalyzer
                {
                    Tokenizer = "standard",
                    Filter    = new[] { "lowercase", "czech_stop", "czech_stemmer", "asciifolding" }
                };
                set.Analysis = new Analysis()
                {
                    Analyzers    = new Analyzers(),
                    TokenFilters = new TokenFilters(),
                };
                set.Analysis.Analyzers.Add("default", an);
                set.Analysis.TokenFilters.Add("czech_stop", new StopTokenFilter()
                {
                    StopWords = new string[] { "_czech_" }
                });
                set.Analysis.TokenFilters.Add("czech_stemmer", new StemmerTokenFilter()
                {
                    Language = "czech"
                });
                var idxSt = new IndexState {
                    Settings = set
                };

                var res = client
                          .CreateIndex(client.ConnectionSettings.DefaultIndex, i => i
                                       .InitializeUsing(idxSt)
                                       .Mappings(m =>
                {
                    switch (db)
                    {
                    case Database.Dokument:
                        return(m.Map <Dokument>(map => map.AutoMap().DateDetection(false)));

                    case Database.Osoba:
                        return(m.Map <Osoba>(map => map.AutoMap().DateDetection(false)));

                    case Database.Rizeni:
                        return(m.Map <Rizeni>(map => map.AutoMap().DateDetection(false)));

                    default:
                        throw new ArgumentOutOfRangeException($"Unknown DB type {db.ToString()}");
                    }
                })
                                       );
            }
        }
Beispiel #31
0
        public void Init()
        {
            var sIndex = new IndexState();
            var qIndex = new IndexQueries(sIndex);
            var hIndex = new IndexEventhandlers(sIndex);

            WhenIndex = new Example.Index(qIndex,hIndex);
            GivenIndex = WhenIndex.Handle;
            ThenIndex = new Mock<Contracts.Index.IHandleEvents>();
            WhenIndex.Handle = ThenIndex.Object;
        }
Beispiel #32
0
        public SetIndexStateCommand([NotNull] string name, IndexState state, string databaseName)
            : base(databaseName)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new RachisApplyException($"Index name cannot be null or empty");
            }

            State     = state;
            IndexName = name;
        }
Beispiel #33
0
 public void Init()
 {
     var sIndex = new IndexState();
     var qIndex = new IndexQueries(sIndex);
     var hIndex = new IndexEventhandlers(sIndex);
     var qMembership = new MembershipQueries(qIndex);
     var hMembership = new MembershipEventhandlers(hIndex);
     When = new Membership(qMembership,hMembership);
     Given = When.Handle;
     Then = new Mock<Contracts.Membership.IHandleEvents>();
     When.Handle = Then.Object;
 }
Beispiel #34
0
        public void Init()
        {
            var sIndex = new IndexState();
            var qIndex = new IndexQueries(sIndex);
            var hIndex = new IndexEventhandlers(sIndex);

            GivenMembership = new MembershipEventhandlers(hIndex);

            var sProject = new ProjectState();
            var qProject = new ProjectQueries(qIndex);
            var hProject = new ProjectEventhandlers(sProject, hIndex);

            WhenProject = new Project(qProject, hProject);
            GivenProject = WhenProject.Handle;
            ThenProject = new Mock<Contracts.Projects.IHandleEvents>();
            WhenProject.Handle = ThenProject.Object;
        }
 public IndexStatusResponse(IndexState Status) : this() {
   this.Status = Status;
 }