public async Task <TEntity> FindAsync(Guid id)
        {
            var nestId   = (id as Guid?).Value;
            var response = await ElasticClient.GetAsync(DocumentPath <TEntity> .Id(nestId).Index(IndexName));

            return(response.Source);
        }
Пример #2
0
        public static bool updateListUser(string ID, List <long> LstUserId, string Type)
        {
            if (EnableElasticServer.ToIntOrZero() == 1)
            {
                try
                {
                    var result = ConnectionToES.EsClient().Get <ElasticModel>(Type + "_" + ID.ToString(),
                                                                              x => x.Index(ElasticIndex).Type(ElasticModel));
                    ElasticModel tmpModel = result.Source;
                    if (LstUserId != null && LstUserId.Count > 0)
                    {
                        tmpModel.ListUser.AddRange(LstUserId);
                        var response = ConnectionToES.EsClient().Update(
                            DocumentPath <ElasticModel> .Id(Type + "_" + ID.ToString()),
                            u => u.Index(ElasticIndex).Type(ElasticModel).Doc(tmpModel)
                            );
                        return(true);
                    }
                    return(false);
                }
                catch (Exception ex)
                {
                    return(false);
                }
            }

            return(false);
        }
Пример #3
0
        public async Task DeleteAsync(Guid id, CancellationToken cancellationToken = default)
        {
            ValidateElasticSearchEnabled();

            HandleError(await _clientProvider.GetClient()
                        .DeleteAsync(DocumentPath <Document> .Id(id), x => x.Index(_options.IndexName), cancellationToken));
        }
Пример #4
0
        /// <summary>
        /// Update a Document Using id For An Index.
        /// </summary>
        /// <param name="gff"></param>
        public void UpdateDataToElk(RetailGroupFoolFallElk gff)
        {
            try
            {
                var uri      = new Uri("http://127.0.0.1:9200/");
                var settings = new ConnectionSettings(uri);
                var client   = new ElasticClient(settings);
                var day      = DateTimeOffset.Now.Day;
                var month    = DateTimeOffset.Now.Month;
                var year     = DateTimeOffset.Now.Year;

                string indexType    = "elktest1_20201216";
                var    DateInString = String.Concat(year, month, day);
                var    indexName    = String.Concat(indexType, "_", DateInString);

                //dynamic updateDoc = new System.Dynamic.ExpandoObject();
                //updateDoc.Title = "My new title";

                var response = client.Update(DocumentPath <RetailGroupFoolFallElk>
                                             .Id("nKt5anYBivAaQj_VvueF"),
                                             u => u
                                             .Index(indexType)
                                             .DocAsUpsert(true)
                                             .Doc(gff)

                                             );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #5
0
        public async Task <DocumentResponse <TEntity> > GetEntityByIdAsync <TEntity>(Id id)
            where TEntity : class
        {
            var result = new DocumentResponse <TEntity>();

            var indexName = ElasticSearchExtensions.GetIndexNameFrom <TEntity>();

            var indexExistsResponse = await _elasticClient.Indices.ExistsAsync(indexName)
                                      .ConfigureAwait(false);

            if (!indexExistsResponse.Exists)
            {
                result.IsOk         = false;
                result.ErrorMessage = $"Index {indexName} does not exist";

                return(result);
            }

            var documentPath = DocumentPath <TEntity> .Id(id);

            var getResponse = await _elasticClient.GetAsync(documentPath, descriptor => descriptor.Index(indexName))
                              .ConfigureAwait(false);

            if (!getResponse.IsValid)
            {
                result.IsOk         = false;
                result.ErrorMessage = getResponse.OriginalException.Message;
                result.Exception    = getResponse.OriginalException;
                return(result);
            }

            result.DocumentResult = getResponse;

            return(result);
        }
Пример #6
0
        public async Task AddOrUpdateAsync(Document document, CancellationToken cancellationToken = default)
        {
            ValidateElasticSearchEnabled();

            var client = _clientProvider.GetClient();

            var existsResponse = await client.DocumentExistsAsync(DocumentPath <EsDocument> .Id(document.Id),
                                                                  x => x.Index(_options.IndexName), cancellationToken);

            HandleError(existsResponse);

            var esDocument = new EsDocument
            {
                Id           = document.Id,
                ProjectId    = document.ProjectId,
                Name         = document.Name,
                FileName     = document.FileName,
                Content      = document.Content,
                LanguageCode = ConvertLanguageCode(document.LanguageCode),
                Version      = ConvertVersion(document.Version)
            };

            if (!existsResponse.Exists)
            {
                HandleError(await client.IndexAsync(esDocument,
                                                    x => x.Id(document.Id).Index(_options.IndexName), cancellationToken));
            }
            else
            {
                HandleError(await client.UpdateAsync(DocumentPath <EsDocument> .Id(document.Id),
                                                     x => x.Doc(esDocument).Index(_options.IndexName), cancellationToken));
            }
        }
Пример #7
0
        public static void HowToScrollIndex(IElasticClient client)
        {
            var res = client.Search <ProductListEsIndexModelExample>(s => s
                                                                     .From(0)
                                                                     .Size(1)
                                                                     .MatchAll()
                                                                     .Scroll(new Time(TimeSpan.FromSeconds(4)))
                                                                     );

            res.ThrowIfException();
            if (!ValidateHelper.IsPlumpString(res.ScrollId))
            {
                throw new Exception("未能拿到游标地址");
            }

            while (true)
            {
                res = client.Scroll <ProductListEsIndexModelExample>("4s", res.ScrollId);
                if (!res.Documents.Any())
                {
                    break;
                }
                foreach (var doc in res.Documents)
                {
                    //do something
                    client.Delete(new DeleteRequest("index", "typename", "ukey"));
                    client.Delete(DocumentPath <ProductListEsIndexModelExample> .Id("ukey").Index("index"));
                }
            }
        }
Пример #8
0
        //** if you have an instance of your document you can use it as well generate document paths */
        [U] public void FromObject()
        {
            var project = new Project {
                Name = "hello-world"
            };

            /** here we create a new document path based on a Project */
            IDocumentPath path = new DocumentPath <Project>(project);

            Expect("project").WhenSerializing(path.Index);
            Expect("project").WhenSerializing(path.Type);
            Expect("hello-world").WhenSerializing(path.Id);

            /** You can still override the inferred index and type name*/
            path = new DocumentPath <Project>(project).Type("project1");
            Expect("project1").WhenSerializing(path.Type);

            path = new DocumentPath <Project>(project).Index("project1");
            Expect("project1").WhenSerializing(path.Index);

            /** there is also a static way to describe such paths */
            path = DocumentPath <Project> .Id(project);

            Expect("project").WhenSerializing(path.Index);
            Expect("project").WhenSerializing(path.Type);
            Expect("hello-world").WhenSerializing(path.Id);

            DocumentPath <Project> p = project;
        }
Пример #9
0
        /// <summary>
        /// 保存
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="indexName">索引名</param>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public virtual async Task SaveAsync <T>(string indexName, T entity) where T : class
        {
            var client = await GetClientAsync();

            var exists =
                await client.DocumentExistsAsync(DocumentPath <T> .Id(new Id(entity)), dd => dd.Index(indexName));

            if (exists.Exists)
            {
                var result = await client.UpdateAsync(DocumentPath <T> .Id(new Id(entity)),
                                                      ss => ss.Index(indexName).Doc(entity).RetryOnConflict(3));

                if (result.ServerError == null)
                {
                    return;
                }

                throw new ElasticSearchException($"更新文档在索引 {indexName} 失败:{result.ServerError.Error.Reason}");
            }
            else
            {
                var result = await client.IndexAsync <T>(entity, ss => ss.Index(indexName));

                if (result.ServerError == null)
                {
                    return;
                }
                throw new ElasticSearchException($"插入文档在索引 {indexName} 失败:{result.ServerError.Error.Reason}");
            }
        }
Пример #10
0
        public virtual async Task AddOrUpdateAsync <T, TKey>(string indexName, T model) where T : ElasticEntity <TKey>
        {
            var exis = ElasticSearchClient.DocumentExists(DocumentPath <T> .Id(new Id(model)), dd => dd.Index(indexName));

            if (exis.Exists)
            {
                var result = await ElasticSearchClient.UpdateAsync(DocumentPath <T> .Id(new Id(model)),
                                                                   ss => ss.Index(indexName).Doc(model).RetryOnConflict(3));

                if (result.ServerError == null)
                {
                    return;
                }
                throw new ElasticSearchException($"Update Document failed at index{indexName} :" + result.ServerError.Error.Reason);
            }
            else
            {
                var result = await ElasticSearchClient.IndexAsync(model, ss => ss.Index(indexName));

                if (result.ServerError == null)
                {
                    return;
                }
                throw new ElasticSearchException($"Insert Document failed at index {indexName} :" + result.ServerError.Error.Reason);
            }
        }
        public async Task <bool> AddManyBulk(List <NewYorkAddDtos> newYorkList)
        {
            List <NewYorkAddDtos> tempList = new List <NewYorkAddDtos>();

            foreach (var newYork in newYorkList)
            {
                ISearchResponse <NewYork> searchResponse = await Exists(newYork.id);

                if (searchResponse != null)
                {
                    var updateResponse = await _client.UpdateAsync <NewYorkAddDtos>(
                        DocumentPath <NewYorkAddDtos> .Id(searchResponse.Hits.FirstOrDefault().Id),
                        descriptor => descriptor
                        .RetryOnConflict(3)
                        .Doc(newYork)
                        .Refresh(Refresh.True)
                        );
                }
                else
                {
                    tempList.Add(newYork);
                }
            }

            if (tempList.Count > 0)
            {
                var indexManyAsyncResponse = await _client.IndexManyAsync(tempList);

                return(indexManyAsyncResponse.IsValid);
            }
            else
            {
                return(true);
            }
        }
Пример #12
0
        public Task <Response> DeleteEntityAsync <TEntity>(Id id)
            where TEntity : class
        {
            var documentPath = DocumentPath <TEntity> .Id(id);

            return(DeleteEntityFromPathAsync(documentPath));
        }
        public async Task <bool> UpdateData(NewYorkUpdateDtos newYorkUpdateDtos, int id)
        {
            ISearchResponse <NewYork> searchResponse = await Exists(id);

            if (searchResponse != null)
            {
                var newYork        = searchResponse.Documents.FirstOrDefault();
                var updateResponse = await _client.UpdateAsync <NewYorkUpdateDtos>(
                    DocumentPath <NewYorkUpdateDtos> .Id(searchResponse.Hits.FirstOrDefault().Id),
                    descriptor => descriptor
                    .RetryOnConflict(3)
                    .Doc(newYorkUpdateDtos)
                    .Refresh(Refresh.True)
                    );

                if (updateResponse.IsValid)
                {
                    return(true);
                }

                return(false);
            }



            return(false);
        }
Пример #14
0
        public async Task DeleteAsync <T>(string id)
            where T : class
        {
            await Client.DeleteAsync(DocumentPath <T> .Id(id), idx => idx.Index(PrefixIndex + "-" + typeof(T).Name.ToLower()));

            await Client.RefreshAsync(Indices.All);
        }
Пример #15
0
 public async Task Update(Identity.Identity identity)
 {
     var client = GetClient();
     var model  = From(identity);
     await client.UpdateAsync(DocumentPath <Model.Identity> .Id(model.Id),
                              u => u.Doc(model)
                              );
 }
Пример #16
0
 internal void Update(T data, UpdateAction action, Expression <Func <T, IList> > fields, bool immediately = true)
 {
     if (!CheckExist(data))
     {
         return;
     }
     Client.Instance.Update(DocumentPath <T> .Id(data), r => GetMetaForUpdate(r, data, action, fields, immediately));
 }
Пример #17
0
 internal void Update(T data, bool immediately = true, params Expression <Func <T, object> >[] fields)
 {
     if (!CheckExist(data))
     {
         return;
     }
     Client.Instance.Update(DocumentPath <T> .Id(data), r => GetMetaForUpdate(r, data, immediately, fields));
 }
        public async Task <DraftSuggestions> Get(Guid id)
        {
            var client = GetClient();
            var model  = await client.GetAsync(DocumentPath <Model.DraftSuggestions> .Id(id));

            CheckResponse(model, id);
            return(To(model.Source));
        }
        private async Task <CustomerQueryModel> GetCustomerAsync(Guid customerId)
        {
            var contract = (await _elasticClient.GetAsync(DocumentPath <CustomerQueryModel>
                                                          .Id(customerId)
                                                          .Index(IndexName)))
                           .Source;

            return(contract);
        }
        public async Task UpdatePartAsync <TPart>(TPart upsertData) where TPart : class, IEntity
        {
            await ElasticClient.UpdateAsync <TEntity, TPart>(DocumentPath <TEntity> .Id(upsertData.Id),
                                                             descriptor => descriptor
                                                             .Doc(upsertData)
                                                             .Index(IndexName));

            await ElasticClient.RefreshAsync(IndexName);
        }
        public async Task DeleteAsync(TEntity entity)
        {
            var nestId = ((entity).Id as Guid?).Value;

            await ElasticClient.DeleteAsync(DocumentPath <TEntity> .Id(((IEntity)entity).Id)
                                            .Index(IndexName));

            await ElasticClient.RefreshAsync(IndexName);
        }
 public void Handle(ProductUpdatedEvent notification)
 {
     var response = _elasticClient.Update(DocumentPath <ProductUpdatedEvent>
                                          .Id(notification.Id),
                                          u => u
                                          .Index("alias-product")
                                          .Type("product")
                                          .DocAsUpsert(true)
                                          .Doc(notification));
 }
Пример #23
0
 public Genre UpdateGenre(Genre genre)
 {
     _elasticClient.Update(
         DocumentPath <Genre> .Id(genre.Id),
         update => update.Index(GENRE_INDEX)
         .DocAsUpsert()
         .Doc(genre)
         );
     return(genre);
 }
Пример #24
0
        public async Task UpdateBlogTagAsync(TagEventArgs e)
        {
            var result = await _client.UpdateAsync <BlogIndexed, object>(DocumentPath <BlogIndexed> .Id(e.Blog.BlogID), ud => ud.Doc(new { tags = e.Model, e.Blog.isHarmony }).Refresh(Elasticsearch.Net.Refresh.True));

            if (!result.IsValid)
            {
                _logger.LogError(result.DebugInformation);
                await AddOrUpdateBlogAsync(new BlogEventArgs(e.Blog, e.Model));
            }
        }
Пример #25
0
 public static async Task UpsertSearch(IElasticClient client, string templateId, IDictionary <string, object> search)
 {
     var indexName = client.ConnectionSettings.DefaultIndices[typeof(TemplateSearch)];
     var _         = await client.UpdateAsync(
         DocumentPath <object> .Id(templateId), x => x
         .Index(indexName)
         .Doc(search)
         .DocAsUpsert()
         .RetryOnConflict(5));
 }
Пример #26
0
        protected virtual void RemoveCore(IElasticClient client, TUmbracoEntity entity,
                                          string indexName = null)
        {
            var idValue      = IdFor(entity);
            var documentPath = DocumentPath <TUmbracoDocument> .Id(idValue);

            if (client.DocumentExists(documentPath, d => d.Index(indexName)).Exists)
            {
                client.Delete(documentPath, d => d.Index(indexName));
            }
        }
Пример #27
0
        /// <summary>
        /// Deletes existing document
        /// </summary>
        /// <param name="id">Guid for document</param>
        /// <returns></returns>
        public async Task <bool> Delete(Guid id)
        {
            var response = await _client.DeleteAsync <Models.Quest>(DocumentPath <Models.Quest> .Id(id), d => d.Index("quest"));

            if (response.Found)
            {
                return(true);
            }

            return(false);
        }
Пример #28
0
        public async Task DeleteAsync(TUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            await Client.DeleteAsync(DocumentPath <TUser> .Id(user.Id), d => d
                                     .Version(user.Version)
                                     .Refresh(Refresh.True));
        }
Пример #29
0
        private static async Task <Pessoa> Consultar(ElasticClient elasticClient, int id)
        {
            var response = await elasticClient.GetAsync(DocumentPath <Pessoa> .Id(new Id(id)));

            if (response.Found)
            {
                return(response.Source);
            }

            return(null);
        }
Пример #30
0
        public object UpdateDocument <T>(int id, ElasticClient es, T obj, IndexName name) where T : BaseClass
        {
            var response = es.Update(DocumentPath <T>
                                     .Id(id),
                                     u => u
                                     .Index(name)
                                     .DocAsUpsert(true)
                                     .Doc(obj));

            return(response);
        }