コード例 #1
0
        public async Task <T> Get(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }
            var existsResponse = await _client.DocumentExistsAsync <T>(id, d => d.Index(_defaultIndex).Type(_defaultTypeName));

            if (!existsResponse.Exists)
            {
                return(default(T));
            }
            var response = await _client.GetAsync <T>(id, s => s.Index(_defaultIndex).Type(_defaultTypeName));

            if (!response.IsValid)
            {
                throw new DataException <T>(
                          "Get",
                          Mapper.Map <Models.Result>(Nest.Result.Error),
                          $"{response.OriginalException.Message}{Environment.NewLine}{response.ServerError}{Environment.NewLine}{response.DebugInformation}",
                          response.OriginalException
                          );
            }
            return(response.Source);
        }
コード例 #2
0
        private async Task <Response> DeleteEntityFromPathAsync <TEntity>(DocumentPath <TEntity> documentPath)
            where TEntity : class
        {
            var result    = new Response();
            var indexName = ElasticSearchExtensions.GetIndexNameFrom <TEntity>();

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

            if (!existsResponse.Exists)
            {
                throw new InvalidOperationException($"Index {indexName} does not exist");
            }

            var documentExistsResponse = await _elasticClient.DocumentExistsAsync(documentPath, d => d.Index(indexName))
                                         .ConfigureAwait(false);

            if (!documentExistsResponse.Exists)
            {
                return(result);
            }

            var deleteResponse = await _elasticClient.DeleteAsync(documentPath, d => d.Index(indexName))
                                 .ConfigureAwait(false);

            if (deleteResponse.IsValid)
            {
                return(result);
            }

            result.IsOk         = false;
            result.ErrorMessage = deleteResponse.OriginalException.Message;
            result.Exception    = deleteResponse.OriginalException;
            return(result);
        }
        public async Task <bool> ExistsAsync(Id id)
        {
            if (String.IsNullOrEmpty(id.Value))
            {
                return(false);
            }

            if (!HasParent || id.Routing != null)
            {
                var response = await _client.DocumentExistsAsync <T>(new DocumentPath <T>(id.Value), d => {
                    d.Index(GetIndexById(id));
                    if (id.Routing != null)
                    {
                        d.Routing(id.Routing);
                    }

                    return(d);
                }).AnyContext();

                _logger.Trace(() => response.GetRequest());

                return(response.Exists);
            }
            else
            {
                return(await ExistsAsync(q => q.Id(id)).AnyContext());
            }
        }
コード例 #4
0
        public async Task <IActionResult> PostAsync([FromBody] News model, CancellationToken cancellationToken)
        {
            if (model is null)
            {
                return(BadRequest());
            }
            var response = await _elasticClient.DocumentExistsAsync <News>(model.NId.ToString(), ct : cancellationToken);

            if (response.Exists)
            {
                return(BadRequest());
            }
            var entity = await _elasticClient.IndexDocumentAsync(model, cancellationToken);

            return(Ok(model));
        }
コード例 #5
0
        public virtual async Task <bool> ExistsAsync(Id id)
        {
            if (String.IsNullOrEmpty(id.Value))
            {
                return(false);
            }

            if (!HasParent || id.Routing != null)
            {
                var response = await _client.DocumentExistsAsync(new DocumentPath <T>(id.Value), d => {
                    d.Index(GetIndexById(id));
                    if (id.Routing != null)
                    {
                        d.Routing(id.Routing);
                    }

                    return(d);
                }).AnyContext();

                if (_logger.IsEnabled(Microsoft.Extensions.Logging.LogLevel.Trace))
                {
                    _logger.LogTrace(response.GetRequest());
                }

                return(response.Exists);
            }

            return(await ExistsAsync(q => q.Id(id)).AnyContext());
        }
コード例 #6
0
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        public static async Task <bool> DocExistAsync_ <T>(this IElasticClient client, string indexName, string uid) where T : class, IElasticSearchIndex
        {
            var response = await client.DocumentExistsAsync(client.ID <T>(indexName, uid));

            response.ThrowIfException();
            return(response.Exists);
        }
コード例 #7
0
        /// <summary>
        /// 是否存在指定文档标识
        /// </summary>
        /// <typeparam name="TDocument">文档类型</typeparam>
        /// <param name="id">文档标识</param>
        /// <param name="index">索引名称。注意:必须小写</param>
        /// <param name="cancellationToken">取消令牌</param>
        public async Task <bool> ExistsAsync <TDocument>(object id, string index = null, CancellationToken cancellationToken = default) where TDocument : class
        {
            index = GetIndexName(Helper.SafeIndexName <TDocument>(index));
            var response = await _client.DocumentExistsAsync <TDocument>(Helper.GetEsId(id), ct : cancellationToken);

            return(response.Exists);
        }
コード例 #8
0
        public async Task <UserAccount> CreateUserAsync(string userId, IEnumerable <Claim> claims)
        {
            var user = new UserAccount
            {
                UserId        = userId,
                AccountClaims = claims.Select(c => new AccountClaim(c)).ToList()
            };
            var existsResponse = await _client.DocumentExistsAsync <UserAccount>(user);

            if (existsResponse.Exists)
            {
                throw new UserAccountExistsException(userId);
            }
            await _client.IndexDocumentAsync(user);

            await _client.RefreshAsync(Indices.Index <UserAccount>());

            return(user);
        }
コード例 #9
0
        public async Task <bool> ContainsKeyAsync(string key, CancellationToken cancellationToken = default)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var response = await ElasticClient.DocumentExistsAsync <T>(key, d => d
                                                                       .Index(Mapping.Index),
                                                                       cancellationToken);

            return(response.Exists);
        }
コード例 #10
0
        public async Task <IActionResult> InsertDoc([FromBody] AppUser u)
        {
            //判断索引是否存在
            var indexExist = await _esClient.IndexExistsAsync("users");

            //判断文档是否存在,这里是根据索引名字(数据库),索引type(表),和该文档的id来判断的(主键)
            IExistsResponse existsResponse = await _esClient.DocumentExistsAsync(new DocumentExistsRequest("users", "appuser", u.Id));

            if (indexExist.Exists && !existsResponse.Exists)
            {
                ////创建索引users,如果索引不存在会自动创建,并将上面user的值写入该索引的文档
                var response = await _esClient.IndexAsync(u, index =>
                {
                    return(index.Index("users"));
                });

                //写入成功
                if (response.IsValid)
                {
                    return(Ok());
                }
            }
            return(BadRequest());
        }
コード例 #11
0
        public async Task ReIndexUpdate()
        {
            var products = productRepository.GetAll().ToArray();

            foreach (var product in products)
            {
                var any = await elasticClient.DocumentExistsAsync <ProductViewModel>(product.ProductCode);

                if (!any.Exists)
                {
                    await elasticClient.IndexDocumentAsync(product);

                    continue;
                }
                await elasticClient.UpdateAsync <ProductViewModel>(product.ProductCode, u => u.Index(defaultIndex).Doc(product));
            }
        }
コード例 #12
0
 protected override Task <IExistsResponse> ExecuteCoreAsync(IElasticClient client, string index)
 {
     return(client.DocumentExistsAsync <T>(DocumentPath <T> .Id(_id), desc => BuildQueryCore(desc).Index(index)));
 }
コード例 #13
0
 public async Task <Boolean> Exists <T>(Id id) where T : class
 {
     _readsMeter.Mark();
     return((await _client.DocumentExistsAsync <T>(id)).Exists);
 }
コード例 #14
0
 protected override async Task <IExistsResponse> ExecuteCoreAsync(IElasticClient client, string index)
 {
     return(await client.DocumentExistsAsync(DocumentPath <T> .Id(_document), desc => BuildQueryCore(desc).Index(index)).ConfigureAwait(false));
 }
コード例 #15
0
 public async Task <bool> Exists <T>(Id id) where T : class
 {
     ReadsMeter.Mark();
     Logger.Debug("Checking if document {0} exists", id.GetString(_client.ConnectionSettings));
     return((await _client.DocumentExistsAsync <T>(id).ConfigureAwait(false)).Exists);
 }
コード例 #16
0
        public async Task <IActionResult> Index()
        {
            // Text from public domain books.  Can be downloaded from multiple sources,
            // but for example: https://dp.la
            var books = new List <Book>()
            {
                new Book
                {
                    Id      = 1,
                    Title   = "Narrative of the Life of Frederick Douglass",
                    Opening = "I was born in Tuckahoe, near Hillsborough, and about twelve miles from Easton, in Talbot county, Maryland. I have no accurate knowledge of my age, never having seen any authentic record containing it. By far the larger part of the slaves know as little of their ages as horses know of theirs, and it is the wish of most masters within my knowledge to keep their slaves thus ignorant.",
                    Genre   = BookGenre.Biography,
                    Author  = new Author
                    {
                        FirstName = "Frederick",
                        LastName  = "Douglass"
                    },
                    InitialPublishYear = 1845
                },
                new Book
                {
                    Id      = 2,
                    Title   = "A Tale of Two Cities",
                    Opening = "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way—in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.",
                    Genre   = BookGenre.HistoricalFiction,
                    Author  = new Author
                    {
                        FirstName = "Charles",
                        LastName  = "Dickens"
                    },
                    InitialPublishYear = 1859
                },
                new Book
                {
                    Id      = 3,
                    Title   = "On the Origin of Species",
                    Opening = "When we compare the individuals of the same variety or sub-variety of our older cultivated plants and animals, one of the first points which strikes us is, that they generally differ more from each other than do the individuals of any one species or variety in a state of nature. And if we reflect on the vast diversity of the plants and animals which have been cultivated, and which have varied during all ages under the most different climates and treatment, we are driven to conclude that this great variability is due to our domestic productions having been raised under conditions of life not so uniform as, and somewhat different from, those to which the parent species had been exposed under nature.",
                    Genre   = BookGenre.Science,
                    Author  = new Author
                    {
                        FirstName = "Charles",
                        LastName  = "Darwin"
                    },
                    InitialPublishYear = 1859
                },
                new Book
                {
                    Id      = 4,
                    Title   = "Oh Pioneers!",
                    Opening = "One January day, thirty years ago, the little town of Hanover, anchored on a windy Nebraska tableland, was trying not to be blown away. A mist of fine snowflakes was curling and eddying about the cluster of low drab buildings huddled on the gray prairie, under a gray sky. The dwelling-houses were set about haphazard on the tough prairie sod; some of them looked as if they had been moved in overnight, and others as if they were straying off by themselves, headed straight for the open plain.",
                    Genre   = BookGenre.HistoricalFiction,
                    Author  = new Author
                    {
                        FirstName = "Willa",
                        LastName  = "Cather"
                    },
                    InitialPublishYear = 1913
                },
                new Book
                {
                    Id      = 5,
                    Title   = "Moby Dick",
                    Opening = "Call me Ishmael. Some years ago—never mind how long precisely—having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation.",
                    Genre   = BookGenre.Adventure,
                    Author  = new Author
                    {
                        FirstName = "Herman",
                        LastName  = "Melville"
                    },
                    InitialPublishYear = 1851
                }
            };

            foreach (var book in books)
            {
                var existsResponse = await _elasticClient.DocumentExistsAsync <Book>(book);

                // If the document already exists, we're going to update it; otherwise insert it
                // Note:  You may get existsResponse.IsValid = false for a number of issues
                // ranging from an actual server issue, to mismatches with indices (e.g. a
                // mismatch on the datatype of Id).
                if (existsResponse.IsValid && existsResponse.Exists)
                {
                    var updateResponse = await _elasticClient.UpdateAsync <Book>(book, u => u.Doc(book));

                    if (!updateResponse.IsValid)
                    {
                        var errorMsg = "Problem updating document in Elasticsearch.";
                        _logger.LogError(updateResponse.OriginalException, errorMsg);
                        throw new Exception(errorMsg);
                    }
                }
                else
                {
                    var insertResponse = await _elasticClient.IndexDocumentAsync(book);

                    if (!insertResponse.IsValid)
                    {
                        var errorMsg = "Problem inserting document to Elasticsearch.";
                        _logger.LogError(insertResponse.OriginalException, errorMsg);
                        throw new Exception(errorMsg);
                    }
                }
            }

            var vm = new HomeViewModel
            {
                InsertedData = JsonConvert.SerializeObject(books, Formatting.Indented)
            };

            return(View(vm));
        }