private bool DeleteEsData(IEnumerable <UserMessageBoxInfoRelation> relations) { if (relations != null && relations.Any()) { var operations = new List <IBulkOperation>(); var exlogs = ConvertMessageLogToEsLog(relations); foreach (var log in exlogs) { operations.Add(new BulkDeleteOperation <UserMessageBoxInfoRelationC>(log.Id) { Routing = log.UserId }); } var bulkRequest = new BulkRequest(UserMessageBoxRelationIndex) { Operations = operations.ToArray() }; var client = ElasticsearchHelper.CreateClient(); #if DEBUG ElasticsearchHelper.EnableDebug(); #endif var responseOne = client.Bulk(bulkRequest); var errorcount = responseOne.ItemsWithErrors.Count(); DalMessageBox.WriteSyncLogs(relations); return(errorcount <= 0); } return(false); }
public MovieController() { if (!ElasticsearchHelper.EsClient().IndexExists("movies").Exists) { ElasticsearchHelper.CreateMovieIndex(); } }
// GET: Genre public ActionResult Index() { var liste = db.Genre.Include(a => a.Movies).ToList(); try { var response = ElasticsearchHelper.EsClient().Search <Genre>(s => s .Index("genres") .Type("genre") .From(0) .Size(1000) .Query(a => a.MatchAll()) ); ViewBag.Genre = response.Documents; } catch (Exception ex) { throw; } return(View(ViewBag.Genre)); }
public GenreController() { if (!ElasticsearchHelper.EsClient().IndexExists("genres").Exists) { ElasticsearchHelper.CreateGenreIndex(); } }
public static List <ArticleES> GetESArticleBykeyWord(string keyWord) { List <ArticleES> result = new List <ArticleES>(); try { var response = ElasticsearchHelper.CreateClient() .Search <ArticleES>(s => s .Index(articleIndexName) .Type(articleTypeName) .Query(q => q .MultiMatch(t => t .Fields(f => f .Field(ae => ae.title)) .Query(keyWord).MinimumShouldMatch("100%")))); if (response != null && response.IsValid) { result = response.Hits.Select(t => t.Source).ToList(); } } catch (Exception ex) { logger.Error(ex); } return(result); }
public static List <ArticleES> GetESArticleById(int id) { List <ArticleES> result = new List <ArticleES>(); try { var response = ElasticsearchHelper.CreateClient() .Search <ArticleES>(s => s .Index(articleIndexName) .Type(articleTypeName) .Query(m => m .Term(mt => mt .Field(ae => ae.id) .Value(id)))); if (response != null && response.IsValid) { result = response.Hits.Select(t => t.Source).ToList(); } } catch (Exception ex) { logger.Error(ex); } return(result); }
public ActionResult DeleteIndex() { ElasticsearchHelper.DeleteIndex("genres"); string mesaj = "<script language='javascript' type='text/javascript'>alert('Silme İşlemi Başarıyla Gerçekleşmiştir!');window.location.href = '/home/index/';</script>"; return(Content(mesaj)); }
private static async Task Search(ElasticsearchHelper <Product, Guid> elasticsearchHelper, SearchDescriptor <Product> query) { List <Product> result = await elasticsearchHelper.SearchDocumentAsync(query); foreach (Product product in result) { Console.WriteLine(product.Name); } }
protected override void Append(LoggingEvent loggingEvent) { var logline = new ESLogLine(loggingEvent); var client = ElasticsearchHelper.CreateClient(); client.AddToIndex("es_log", new List <ESLogLine>() { logline }); }
public static void Run([TimerTrigger("%CronExpression%")] TimerInfo timerInfo, ExecutionContext context, ILogger log) { var configuration = GetConfiguration(context); var section = configuration.GetSection("Curator"); var settings = section.Get <CuratorSettings>(); Parallel.ForEach( settings.Entries, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 2 }, entry => { log.LogInformation($"Name = {entry.Name}, Endpoint = {entry.Endpoint}"); var client = ElasticsearchHelper.CreateElasticClient(new Uri(entry.Endpoint), settings.RequestTimeout); foreach (var indexEntry in entry.IndexEntries) { IEnumerable <CatIndicesRecord> indices = null; try { indices = ElasticsearchHelper.GetOutOfDateIndices(client, indexEntry, log); } catch (Exception e) { log.LogError(e, $"!!> Error while fetching out-of-date indices (requestTimeout?): {e.Message}"); continue; } foreach (var idx in indices) { if (!settings.WithDryRun) { log.LogInformation($"--> Deleting index '{idx.Index}' (Status = {idx.Status}, DocsCount = {idx.DocsCount}, PrimaryStoreSize = {idx.PrimaryStoreSize}, StoreSize = {idx.StoreSize})"); try { client.DeleteIndex(idx.Index); } catch (Exception e) { log.LogError(e, $"!!> Error while deleting index '{idx.Index}': {e.Message}"); } } else { log.LogInformation($"--> [DRY-RUN] Deleting index '{idx.Index}' (Status = {idx.Status}, DocsCount = {idx.DocsCount}, PrimaryStoreSize = {idx.PrimaryStoreSize}, StoreSize = {idx.StoreSize})"); } } } }); }
// GET: Movie public ActionResult Index(string q) { if (!String.IsNullOrEmpty(q)) { try { var response = ElasticsearchHelper.EsClient().Search <Movie>(p => p .Index("movies") .Type("movie") .Query(a => a.Term(t => t.Description, q)) .Query(a => a.MatchPhrasePrefix(mq => mq.Field(f => f.Title).Query(q))) ); var datasend = (from hits in response.Hits select hits.Source).ToList(); ViewBag.Data = datasend; return(View(ViewBag.Data)); } catch (Exception ex) { throw; } } else { try { var response = ElasticsearchHelper.EsClient().Search <Movie>(s => s .Index("movies") .Type("movie") .From(0) .Size(1000) .Source(a => a.IncludeAll()) .Query(a => a.MatchAll()) ); ViewBag.Data = response.Documents; } catch (Exception ex) { throw; } return(View(ViewBag.Data)); } }
private static void CleanElasticsearch() { var elasticsearchUri = ConfigurationManager.AppSettings["ElasticsearchUri"]; try { ElasticsearchHelper.DeleteIndex(elasticsearchUri); } catch (Exception exp) { Assert.Inconclusive(String.Format("Error occured connecting to ES: Message{0}, StackTrace: {1}", exp.Message, exp.StackTrace)); } }
public ActionResult DeleteConfirmed(int id) { Genre genre = db.Genre.Find(id); db.Genre.Remove(genre); db.SaveChanges(); var response = ElasticsearchHelper.EsClient().Delete <Genre>(id, d => d .Index("genres") .Type("genre") .Refresh(Elasticsearch.Net.Refresh.True)); return(RedirectToAction("Index")); }
public ActionResult Create([Bind(Include = "Id,Name,Description")] Genre genre) { if (ModelState.IsValid) { db.Genre.Add(genre); db.SaveChanges(); ElasticsearchHelper.EsClient().Index <Genre>(genre, id => id.Index("genres") .Type(TypeName.From <Genre>()) .Id(genre.Id) .Refresh(Elasticsearch.Net.Refresh.True)); return(RedirectToAction("Index")); } return(View(genre)); }
/// <summary> /// job执行结束之后调用 /// </summary> /// <param name="context"></param> /// <param name="jobException"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default) { string msg = string.Format("“{0}”执行结束之后调用,结束时间:{1}", context.JobDetail.Key.Name, DateTime.Now); ELog log = new ELog() { Id = long.Parse(DateTime.Now.ToString("yyyyMMddHHmmss")), JobName = context.JobDetail.Key.Name, ExecTime = DateTime.Now }; if (jobException != null) { log.ExceptionMessage = string.Format("Source:{0},Message:{1}", jobException.Source, jobException.Message); } ElasticsearchHelper.Add(log); logger.LogWarning(msg); await Console.Out.WriteLineAsync(msg); }
private void DeleteESGroupBuyingProducts(List <ESGroupBuyingProduct> products) { var client = ElasticsearchHelper.CreateClient(); var response = client.Bulk(new BulkRequest("pintuanproduct") { Operations = products.Select <ESGroupBuyingProduct, IBulkOperation>(item => new BulkDeleteOperation <ESGroupBuyingProduct>(item) { Routing = item.ProductGroupId }).ToList() }); if (!response.IsValid) { var productGroupId = products.Select(p => p.ProductGroupId).FirstOrDefault(); Logger.Warn($"{productGroupId} ES数据删除失败:{JsonConvert.SerializeObject(response.ItemsWithErrors)}"); } }
public ActionResult Create([Bind(Include = "Id,Title,Description,CreatedDate,GenreId")] Movie movie) { if (ModelState.IsValid) { movie.CreatedDate = DateTime.Now; db.Movie.Add(movie); db.SaveChanges(); ElasticsearchHelper.EsClient().Index <Movie>(movie, id => id.Index("movies") .Type(TypeName.From <Movie>()) .Id(movie.Id) .Refresh(Elasticsearch.Net.Refresh.True)); return(RedirectToAction("Index")); } ViewBag.GenreID = new SelectList(db.Genre, "ID", "Name", movie.GenreId); return(View(movie)); }
public ActionResult Edit([Bind(Include = "Id,Name,Description")] Genre genre) { if (ModelState.IsValid) { db.Entry(genre).State = EntityState.Modified; db.SaveChanges(); var response = ElasticsearchHelper.EsClient().Update <Genre, Genre>(genre.Id, d => d .Index("genres") .Type("genre") .Refresh(Elasticsearch.Net.Refresh.True) .Doc(new Genre { Id = genre.Id, Name = genre.Name, Description = genre.Description })); return(RedirectToAction("edit")); } return(View(genre)); }
private List <ESGroupBuyingProduct> GetESGroupBuyingProducts(string productGroupId) { var array = new List <Func <QueryContainerDescriptor <ESGroupBuyingProduct>, QueryContainer> > { q => q.Term(f => f.Field(fd => fd.ProductGroupId).Value(productGroupId)) }; var client = ElasticsearchHelper.CreateClient(); var response = client.Search <ESGroupBuyingProduct>( s => s.Index("pintuanproduct") .Type("GroupBuyingProduct") .Query(q => q.Bool(qb => qb.Must(array))) .Size(100)); var esProducts = new List <ESGroupBuyingProduct>(); if (response.IsValid && response.Documents?.Any() == true) { esProducts = response.Documents.ToList(); } return(esProducts); }
public ActionResult Edit([Bind(Include = "Id,Title,Description,CreatedDate,GenreId")] Movie movie) { if (ModelState.IsValid) { db.Entry(movie).State = EntityState.Modified; db.SaveChanges(); var response = ElasticsearchHelper.EsClient().Update <Movie, Movie>(movie.Id, d => d .Index("movies") .Type("movie") .Refresh(Elasticsearch.Net.Refresh.True) .Doc(new Movie { Id = movie.Id, Title = movie.Title, Description = movie.Description, GenreId = movie.GenreId, CreatedDate = DateTime.Now })); return(RedirectToAction("Index")); } ViewBag.GenreID = new SelectList(db.Genre, "ID", "Name", movie.GenreId); return(View(movie)); }
public void Execute(IJobExecutionContext context) { Logger.Info($"刷新开始执行"); int count = 0; int maxpkid = 0; int exceptioncount = 0; string runtimename = "HandleExpiredMessageBox"; var result = CheckIsOpenWithDescription(runtimename); if (!result.Item1) { Logger.Info("开关已关,return"); return; } int.TryParse(result.Item2, out maxpkid); #if DEBUG maxpkid = 0; #endif Logger.Info($"maxpkid:{maxpkid}"); var starttime = DateTime.Now; while (true && count <= 554948) { count++; try { result = CheckIsOpenWithDescription(runtimename); if (!result.Item1) { Logger.Info("开关已关,return"); return; } Logger.Info($"第{count}批次循环刷新开始执行,maxpkid:{maxpkid}"); var relations = SelectMessageRelation(maxpkid, starttime); if (relations != null && relations.Any()) { maxpkid = relations.Max(x => x.PKID); var operations = new List <IBulkOperation>(); var exlogs = ConvertMessageLogToEsLog(relations); foreach (var log in exlogs) { operations.Add(new BulkDeleteOperation <UserMessageBoxInfoRelationC>(log.Id) { Routing = log.UserId }); } var bulkRequest = new BulkRequest(DeleteExpiredMessageBoxJob.UserMessageBoxRelationIndex) { Operations = operations.ToArray() }; var client = ElasticsearchHelper.CreateClient(); #if DEBUG ElasticsearchHelper.EnableDebug(); #endif var responseOne = client.Bulk(bulkRequest); var errorcount = responseOne.ItemsWithErrors.Count(); WriteSyncLogs(relations); UpdateRunTimeSwitchDescription(runtimename, maxpkid.ToString()); Logger.Info($"第{count}批次结束刷新.errorcount:{errorcount}"); } else { break; } } catch (System.Exception ex) { maxpkid -= 1000; Logger.Warn(ex); exceptioncount++; if (exceptioncount >= 10) { break; } } } Logger.Info($"刷新结束"); }
public static async Task <bool> InsertOrUpdateES(Article article) { var result = false; if (ConfigurationManager.AppSettings["IsOpen"] == "true") { try { if (article.Type == 1 || article.Type == 0 || article.Status == ArticleStatus.Published.ToString() || article.Status == ArticleStatus.Withdrew.ToString()) { var createIndex = await ElasticsearchHelper.CreateClient() .CreateIndexIfNotExistsAsync(articleIndexName, c => c .Settings(cs => cs.NumberOfShards(2).NumberOfReplicas(1)) //设置副本和分片数 .Mappings(cm => cm.MapDefault() .Map <ArticleES>(m => m .AutoMap())) ); if (createIndex) { if (article.IsShow == 1 || article.Status == ArticleStatus.Published.ToString()) { var response = await ElasticsearchHelper.CreateClient() .IndexAsync(new ArticleES { id = article.PKID, title = article.SmallTitle, body = "", created_at = article.CreateDateTime.ToString("yyyy-MM-dd HH:mm:ss"), updated_at = article.LastUpdateDateTime.ToString("yyyy-MM-dd HH:mm:ss"), reply_count = "0", view_count = "0", vote_count = "0" }, i => i.Index(articleIndexName).Type(articleTypeName)); if (response.IsValid) { result = true; } } else { var response = await ElasticsearchHelper.CreateClient() .DeleteAsync <ArticleES>(article.PKID.ToString(), d => d.Index(articleIndexName).Type(articleTypeName)); if (response.IsValid) { result = true; } } } } } catch (Exception ex) { logger.Error(ex); } } return(result); }
public static async Task Run() { var product1 = new Product { ID = Guid.NewGuid(), Name = "高露洁牙膏", Price = 20, Desc = "一种牙膏", Producer = "高露洁", Tags = new List <string> { "高效美白", "修复牙齿" } }; var product2 = new Product { ID = Guid.NewGuid(), Name = "佳洁士牙膏", Price = 30, Desc = "一种", Producer = "佳洁士", Tags = new List <string> { "高效美白" } }; var product3 = new Product { ID = Guid.NewGuid(), Name = "冷酸灵牙膏", Price = 40, Desc = "一种牙膏", Producer = "冷酸灵", Tags = new List <string> { "修复牙齿" } }; var elasticsearchHelper = new ElasticsearchHelper <Product, Guid>("http://116.55.251.31:9200"); await elasticsearchHelper.InsertDocumentAsync(product1); await elasticsearchHelper.InsertDocumentAsync(product2); await elasticsearchHelper.InsertDocumentAsync(product3); SearchDescriptor <Product> query = elasticsearchHelper.GetNewQuery(); query = query.From(0).Size(10).Query(q => q.Match(m => m.Field(f => f.Name).Query("牙膏"))); await Task.Delay(2000); await Search(elasticsearchHelper, query); product1.Name = product1.Name + "1"; product2.Name = product2.Name + "1"; product3.Name = product3.Name + "1"; await elasticsearchHelper.UpdateDocumentAsync(product1); await elasticsearchHelper.UpdateDocumentAsync(product2); await elasticsearchHelper.UpdateDocumentAsync(product3); await Task.Delay(2000); await Search(elasticsearchHelper, query); await elasticsearchHelper.DeleteDocumentAsync(product1.ID); await elasticsearchHelper.DeleteDocumentAsync(product2.ID); await elasticsearchHelper.DeleteDocumentAsync(product3.ID); await Task.Delay(2000); await Search(elasticsearchHelper, query); }
/// <summary> /// Constructer used by unit tests /// </summary> /// <param name="elasticsearchHelper">Elasticsearch Helper class instance to use</param> internal DeletedDocumentCountMetricQuery(ElasticsearchHelper elasticsearchHelper) { this.elasticsearchHelper = elasticsearchHelper; }
/// <summary> /// Constructer used by unit tests /// </summary> /// <param name="elasticsearchHelper">Elasticsearch Helper class instance to use</param> internal StoreSizeMetricQuery(ElasticsearchHelper elasticsearchHelper) { this.elasticsearchHelper = elasticsearchHelper; }
public static void DisposeAll() { try { //startup tasks LibStartUpHelper.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //task TaskManager.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //redis RedisConnectionManager.Dispose(); RedisClientManager.Instance.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //关闭rabbitmq RabbitMQClient.DefaultClient.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //关闭rabbitmq ElasticsearchHelper.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //zookeeper ZooKeeperClientManager.Instance.Dispose(); } catch (Exception e) { e.AddErrorLog(); } try { //IOC AppContext.Dispose(); } catch (Exception e) { e.AddErrorLog(); } }
public async static Task <PagedModel <HomePageTimeLineRequestModel> > SelectDiscoveryHomeAsync(string UserId, PagerModel page, int version) { //关注的类目ID List <int> CategoryIds = new List <int>(); //关注的文章ID List <int> ArticleIDs = new List <int>(); //关注的用户ID List <string> AttentionUserIds = new List <string>(); //关注的用户ID 不包含技师和途虎员工 List <string> AttentionUserIdsNoTuhu = new List <string>(); CategoryIds.Add(0); ArticleIDs.Add(0); AttentionUserIdsNoTuhu.Add("jiadeshujuyongyuguolu"); var cids = await DalArticle.SelectMyCategoryId(UserId); if (cids != null && cids.Any()) { CategoryIds = cids.Select(x => x.CategoryId).ToList(); } var atcid = await DalArticle.SelectMyArticleID(UserId); if (atcid != null && atcid.Any()) { ArticleIDs = atcid.Select(x => x.PKID).ToList(); } var atuid = await DalArticle.SelectMyAttentionUserId(UserId); if (atuid != null && atuid.Any()) { AttentionUserIds = atuid.Select(x => x.AttentionUserId).ToList(); if (atuid.Any(x => x.UserIdentity == null || x.UserIdentity == 0)) { AttentionUserIdsNoTuhu = atuid.Where(x => x.UserIdentity == null || x.UserIdentity == 0).Select(x => x.AttentionUserId).ToList(); } } AttentionUserIds.AddRange(new string[] { "{c69cf542-7b0c-8494-8831-c1a9a2fe6388}", "{f8479c14-3bb1-4711-9a38-2626359b8c28}", "{935b3462-9310-59ce-d742-0cbc1c276ebf}", "{81c9ed57-008c-b2ba-53c8-1cc35caf69c0}" }); var types = new List <int> { 1, 2, 5 }; if (version > 1) { types.Add(11); } var client = ElasticsearchHelper.CreateClient(); var b = await client.SearchAsync <DiscoveryArticleModel>(x => x .Index("discoveryarticle") .Type("Discovery") .Query(q => q. Bool(qb => qb. Should( qs => qs. Bool(qsb => qsb. Must(qsbm => qsbm. Terms(qt => qt. Field(qf => qf.AttentionUserIds). Terms(AttentionUserIds)), qsbm => qsbm. Terms(qt => qt. Field(qf => qf.TYPE). Terms(types)) ) ), qs => qs. Bool(qsb => qsb. Must(qsbm => qsbm. Terms(qt => qt. Field(qf => qf.AttentionUserIds). Terms(AttentionUserIdsNoTuhu)), qsbm => qsbm. Terms(qt => qt. Field(qf => qf.TYPE). Terms(3, 4)) ) ), qs => qs. Bool(qsb => qsb. Must( qsbm => qsbm. Terms(qt => qt. Field(qf => qf.PKID). Terms(ArticleIDs)), qsbm => qsbm. Terms(qt => qt. Field(qf => qf.TYPE). Terms(6)), qsbm => qsbm.Bool(qsbmb => qsbmb. Should( qsbmbs => qsbmbs. Term(qt => qt. Field(qf => qf.AuditStatus). Value(2)), qsbmbs => qsbmbs. Term(qt => qt. Field(qf => qf.AttentionUserIds). Value(UserId)))) ) ), qs => qs. Bool(qsb => qsb. Must( qsbm => qsbm. Terms(qt => qt. Field(qf => qf.CategoryId). Terms(CategoryIds)), qsbm => qsbm. Terms(qt => qt. Field(qf => qf.TYPE). Terms(7)) ) ), qs => qs. Bool(qsb => qsb. Must( qsbm => qsbm. Terms(qt => qt. Field(qf => qf.CategoryId). Terms(CategoryIds)), qsbm => qsbm. Terms(qt => qt. Field(qf => qf.TYPE). Terms(8)), qsbm => qsbm.Bool(qsbmb => qsbmb. Should( qsbmbs => qsbmbs. Term(qt => qt. Field(qf => qf.AuditStatus). Value(2)), qsbmbs => qsbmbs. Term(qt => qt. Field(qf => qf.AttentionUserIds). Value(UserId))) ) ) ) ) ) ) .Sort(s => s. Descending(ss => ss.OperateTime)) .Skip((page.CurrentPage - 1) * page.PageSize) .Take(page.PageSize)); page.Total = (int)b.Total; var a = b.Hits.Select(x => x.Source).Select(x => new HomePageTimeLineRequestModel() { PKID = x.PKID, Type = x.TYPE, DistinctId = x.DISTINCTID, AnswerId = x.AnswerId, AnswerContent = x.AnswerContent, AttentionCount = x.AttentionCount, BigTitle = x.BigTitle, Brief = x.Brief, VoteNum = x.VoteNUm, CategoryId = x.CategoryId, AttentionUserIds = x.AttentionUserIds, CategoryImage = x.CategoryImage, CategoryName = x.CategoryName, CategoryTags = x.CategoryTags, ClickCount = x.ClickCount, CommentImage = x.CommentImage, CommentTimes = x.CommentTimes, Content = x.Content, ContentUrl = x.ContentUrl, CreatorInfo = x.CreatorInfo, OperateTime = x.OperateTime, Praise = x.Praise, RelatedArticleId = x.RelatedArticleId, ShowImages = x.ShowImages, ShowType = x.ShowType, SmallImage = x.SmallImage, SmallTitle = x.SmallTitle, ImagesCount = x.ImagesCount }).ToList(); var groupTypeTimeLine = a.GroupBy(t => new { t.PKID, t.DistinctId, t.Type }).ToList(); var tempTimeLineList = new List <HomePageTimeLineRequestModel>(); //分组拼接所有关注的人 foreach (var timeLine in groupTypeTimeLine) { var tempTimeLine = timeLine.OrderByDescending(t => t.OperateTime).FirstOrDefault(); tempTimeLine.AttentionCount = timeLine.Select(t => t.AttentionUserIds).Distinct().Count(); tempTimeLine.AttentionUserIds = string.Join("、", timeLine.Select(t => t.AttentionUserIds).Distinct().ToArray <string>()); tempTimeLineList.Add(tempTimeLine); } var groupFilterTimeLine = tempTimeLineList.GroupBy(t => new { t.PKID, t.AnswerId }).ToList(); tempTimeLineList.Clear(); //分组去掉重复的数据 foreach (var timeLine in groupFilterTimeLine) { var tempTimeLine = timeLine.OrderByDescending(t => t.OperateTime).FirstOrDefault(); tempTimeLineList.Add(tempTimeLine); } tempTimeLineList = tempTimeLineList.Select(t => t).OrderByDescending(t => t.OperateTime).ToList(); return(new PagedModel <HomePageTimeLineRequestModel>(page, tempTimeLineList));; }
public ESController(ElasticsearchHelper elasticsearchDatabase, ILogger <ESController> Logger) { this._logger = Logger; this._elasticsearchDatabase = elasticsearchDatabase; }
/// <summary> /// Constructer used by unit tests /// </summary> /// <param name="elasticsearchHelper">Elasticsearch Helper class instance to use</param> internal IndexHealthCheck(ElasticsearchHelper elasticsearchHelper) { this.elasticsearchHelper = elasticsearchHelper; }
// public static IMqttClient mqttClient = new MqttFactory().CreateMqttClient(); public static void Main(string[] args) { User u = new User() { UserName = "******", Age = 14 }; TUser user = Map <User, TUser>(u); ServerConfig payconfig = Config.Bind <ServerConfig>("thrift.json", "Pay"); //string s = Redis.RedisHelper.Get("2A6B5EDF418F2046DE43F79E0CCE6773"); // string temp = xElement.ToString(); //int id = 0; //TServerSocket serverTransport = new TServerSocket(8090); //TBinaryProtocol.Factory factory = new TBinaryProtocol.Factory(); //TServerEventHandler handler = new ServerEventHandler(); //TServer server = new TThreadPoolServer(entity, serverTransport, new TTransportFactory(), factory); //server.setEventHandler(handler); //Console.WriteLine(string.Format("服务端正在监听{0}端口", serverPort)); //server.Serve(); //var response = client.Index(tweet, idx => idx.Index("mytweetindex")); //ElasticsearchHelper.Add(tweet); Tweet tweet = new Tweet { Id = 33333, User = "******", Message = "Trying out NEST, so far so good?" }; //ElasticsearchHelper.Add(tweet); // Tweet product33 = ElasticsearchHelper.GetByID<Tweet>(33333); var response = ElasticsearchHelper.Query <ELog>(fs => fs.From(0).Size(100).Query(q => q.Bool(b => b.Filter(f => f.TermRange(r => r.Field(t => t.ExecTime).LessThan("2019-03-22"))))) ); SearchRequest s = new SearchRequest() { From = 0, Size = 100, Query = new BoolQuery() { Filter = new List <QueryContainer>() { new TermRangeQuery() { Field = "ExecTime", LessThan = "2019-03-22" } } } }; var response3 = ElasticsearchHelper.Query <ELog>(s); //product33.User = "******"; //ElasticsearchHelper.Update<Tweet>(product33); ProductIndex product = ElasticsearchHelper.GetByID <ProductIndex>(324); //var options = new MqttClientOptions //{ // ChannelOptions = new MqttClientWebSocketOptions() // { // Uri = "ws://jenkins.miaogo.com.cn:8083/mqtt", // TlsOptions = new MqttClientTlsOptions // { // UseTls = false, // IgnoreCertificateChainErrors = true, // IgnoreCertificateRevocationErrors = true, // AllowUntrustedCertificates = false // } // } //}; //options.CleanSession = true; //options.KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse("60")); //mqttClient.Connected += MqttClient_Connected; //mqttClient.Disconnected += MqttClient_Disconnected; //mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; //MqttClientConnectResult result = mqttClient.ConnectAsync(options).Result; //MqttApplicationMessage appMsg = new MqttApplicationMessage() //{ // Topic = "testtopic", // Payload = Encoding.UTF8.GetBytes("Hello, World!"), // QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, // Retain = false //}; //Task task = MqttHelp<MqttClientTcpOptions>.Subscribe<Test>("topic1", t => //{ // int i = t.Type; //}); //Task tasks = MqttHelp<MqttClientTcpOptions>.Publish<Test>("topic1", new Test() { Type = 3232323 }); //System.Console.ReadLine(); //MqttClientOptions options = new MqttClientOptions //{ // ChannelOptions = new MqttClientTcpOptions() // { // Server = "192.168.3.166", // Port = 1883, // }, // KeepAlivePeriod = TimeSpan.FromSeconds(double.Parse("100")), // ClientId = "zbl", // CleanSession = true //}; //mqttClient = new MqttFactory().CreateMqttClient(); //MqttClientConnectResult result = mqttClient.ConnectAsync(options).Result; //mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived; ; //mqttClient.Connected += MqttClient_Connected; //mqttClient.Disconnected += MqttClient_Disconnected; //var s = mqttClient.SubscribeAsync(new List<TopicFilter> { new TopicFilter("bzs", MqttQualityOfServiceLevel.AtMostOnce) }).Result; //MqttApplicationMessage appMsg = new MqttApplicationMessage() //{ // Topic = "bzs", // Payload = Encoding.UTF8.GetBytes("Hello, World!"), // QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce, // Retain = false //}; //var r = mqttClient.PublishAsync(appMsg); //"", Encoding.UTF8.GetBytes("消息内容"), MqttQualityOfServiceLevel.AtMostOnce, false //var list = DP.Create<ProductShelfRecord>().ToList().AsList(); //RabbitMQService.QueueDelete("1030150513141879784"); //long total = 0; //var sddd = DP.GetPage<Product>(1, 15, out total, "SELECT SaleTime ,SUM(Price) as Price from (SELECT date_format(SaleTime,'%Y-%m-%d') as SaleTime , Price ,SupplierCode from Product where StatusFlag=3 and DeleteFlag=0 and SupplierCode='1040723159508193280' ) as T_Product GROUP BY SaleTime"); //string url = "https://api.weixin.qq.com/sns/oauth2/access_token"; //access_token token = new access_token() //{ // appid = WxConfig.appid, // secret = WxConfig.secret, // code = "021tasN40IlceK1UbAL40FBiN40tasNN", //}; //RestClient client = new RestClient(url); //IRestRequest request = new RestRequest(Method.GET); //request.AddParameter("appid", token.appid); //request.AddParameter("secret", token.secret); //request.AddParameter("code", token.code); //request.AddParameter("grant_type", token.grant_type); //// //IRestResponse<access_tokenresult> response = client.Execute<access_tokenresult>(request); //int count = DP.DeleteEntity<RelationProductCategory>(p => p.Type == 2 && p.Code == "00001"); //string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; //XDocument document = new XDocument(); //XElement root = new XElement("xml"); //root.Add(new XElement("appid", 1)); //root.Add(new XElement("mch_id", 1)); //root.Add(new XElement("device_info", 1)); //root.Add(new XElement("nonce_str", 1)); //root.Add(new XElement("sign_type", 1)); //root.Add(new XElement("body", 1)); //root.Add(new XElement("attach", 1)); //root.Add(new XElement("out_trade_no", 1)); //root.Add(new XElement("fee_type", 1)); //root.Add(new XElement("total_fee", 1)); //root.Add(new XElement("spbill_create_ip", 1)); //root.Add(new XElement("time_start", 1)); //root.Add(new XElement("time_expire", 1)); //root.Add(new XElement("goods_tag", 1)); //root.Add(new XElement("notify_url", 1)); //root.Add(new XElement("trade_type", 1)); //root.Add(new XElement("limit_pay", 1)); //root.Add(new XElement("scene_info", 1)); //document.Add(root); //string xml = document.ToString(); //byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); //System.Net.HttpWebResponse response = null; //byte[] type = HttpHelper.SendRequestData(url, data, ref response); //string t = System.Text.Encoding.UTF8.GetString(type); //CabinetHelp.SendMessage(101, new Cabinet.Entity.CabinetParam() //{ // Queue = "1043041192733970432", // Message= "你好", // Action = new List<object>() { "msg"} //}); //RabbitMQService.Send("1043041192733970432", "33333"); //RabbitMQService.Send("1043041192733970432", "33444"); //RabbitMQService.Send("1043041192733970432", "5555"); //ProductShelfItem shelfItem = new ProductShelfItem() //{ // ShelfCode = "3333", // ShelfType = 1, // ProductName = "", // Price = 0, // ProCount = 2, // CategoryCode = "", // RFIDs = "121212", // ICO = "", // ProductCode = "", // Specifications = "" //}; //transaction.AddTs(shelfItem); //string msg = string.Empty; //int f = DP.SaveEntity(shelfItem); //var config = new ConfigurationBuilder() // .SetBasePath(Directory.GetCurrentDirectory()) // .AddJsonFile("hosting.json", optional: true) // .Build(); //var host = new WebHostBuilder() // .UseConfiguration(config) // .UseKestrel() // .UseStartup<Startup>() // .Build(); //host.Run(); //Config.Bind<CameraConfig>("Camera.json"); ////CameraHelp help = new CameraHelp(); //var result = CameraHelp.Start("C70425683"); }