private static void ExamineResponse(IGetResponse <Album> response) { Console.WriteLine("_index: {0}", response.Index); Console.WriteLine("_type: {0}", response.Type); Console.WriteLine("_id: {0}", response.Id); Console.WriteLine("_version: {0}", response.Version); Console.WriteLine("found: {0}", response.Found); if (response.Source != null) { Console.WriteLine(); Console.WriteLine("_source: "); Console.WriteLine("\tTitle: {0}", response.Source.Title); Console.WriteLine("\tUrl: {0}", response.Source.Url); Console.WriteLine("\tArtist: {0}", response.Source.Artist); Console.WriteLine("\tRank: {0}", response.Source.Rank); Console.WriteLine("\tLabel: {0}", response.Source.Label); Console.WriteLine("\tYear: {0}", response.Source.Year); Console.WriteLine("\tSummary: {0}", response.Source.Summary); Console.WriteLine("\tImageUrl: {0}", response.Source.ImageUrl); } Console.WriteLine("HttpStatusCode: {0}", response.ConnectionStatus.HttpStatusCode); if (response.ConnectionStatus.HttpStatusCode >= 400) { Console.WriteLine(Encoding.UTF8.GetString(response.ConnectionStatus.ResponseRaw)); } Console.WriteLine(); }
protected override void ExpectResponse(IGetResponse <Project> response) { response.Source.Should().NotBeNull(); response.Source.Name.Should().Be(ProjectId); response.Timestamp.HasValue.Should().BeTrue(); response.Ttl.HasValue.Should().BeTrue(); }
/// <summary> /// Retrieve a drug's definition based on its ID. /// <param name="id">The ID of the definition to retrieve.</param> /// <returns>A drug definitions object.</returns> /// </summary> public async Task <DrugTerm> GetById(long id) { IGetResponse <DrugTerm> response = null; try { response = await _elasticClient.GetAsync <DrugTerm>(new DocumentPath <DrugTerm>(id), g => g.Index(this._apiOptions.AliasName).Type("terms")); } catch (Exception ex) { String msg = $"Could not retrieve term id '{id}'."; _logger.LogError($"Error searching index: '{this._apiOptions.AliasName}'."); _logger.LogError(ex, msg); throw new APIErrorException(500, msg); } if (!response.IsValid) { String msg = $"Invalid response when retrieving id '{id}'."; _logger.LogError(msg); throw new APIErrorException(500, msg); } if (null == response.Source) { string msg = $"Not a valid ID '{id}'."; _logger.LogDebug(msg); throw new APIErrorException(404, msg); } return(response.Source); }
/// <summary> /// Get Term details based on the input values /// <param name="dictionary">The value for dictionary.</param> /// <param name="audience">Patient or Healthcare provider</param> /// <param name="language">The language in which the details needs to be fetched</param> /// <param name="id">The Id for the term</param> /// <returns>An object of GlossaryTerm</returns> /// </summary> public async Task <GlossaryTerm> GetById(string dictionary, AudienceType audience, string language, long id) { IGetResponse <GlossaryTerm> response = null; try { string idValue = $"{id}_{dictionary?.ToLower()}_{language?.ToLower()}_{audience.ToString().ToLower()}"; response = await _elasticClient.GetAsync <GlossaryTerm>(new DocumentPath <GlossaryTerm>(idValue), g => g.Index( this._apiOptions.AliasName ).Type("terms")); } catch (Exception ex) { String msg = $"Could not search dictionary '{dictionary}', audience '{audience}', language '{language}' and id '{id}."; _logger.LogError($"Error searching index: '{this._apiOptions.AliasName}'."); _logger.LogError(ex, msg); throw new APIErrorException(500, msg); } if (!response.IsValid) { String msg = $"Invalid response when searching for dictionary '{dictionary}', audience '{audience}', language '{language}' and id '{id}."; _logger.LogError(msg); throw new APIErrorException(500, msg); } if (null == response.Source) { string msg = $"No match for dictionary '{dictionary}', audience '{audience}', language '{language}' and id '{id}."; _logger.LogDebug(msg); throw new APIErrorException(404, msg); } return(response.Source); }
public bool FindDocument(string name, string colname, out JSONDocument doc) { bool found = false; IList <IJSONDocument> jsonDocuments = new List <IJSONDocument>(); doc = new JSONDocument(); if (name != null) { doc.Key = name.ToLower(); jsonDocuments.Add(doc); IGetOperation getOperation = new GetDocumentsOperation(); getOperation.Database = MiscUtil.SYSTEM_DATABASE; getOperation.Collection = colname; getOperation.DocumentIds = jsonDocuments; IGetResponse response = _store.GetDocuments(getOperation); IDataChunk dataChunk = response.DataChunk; if (dataChunk.Documents.Count != 0) { doc = dataChunk.Documents[0] as JSONDocument; found = true; } else { doc = null; found = false; } } return(found); }
/// <summary> /// Get Term deatils based on the input values /// <param name="dictionary">The value for dictionary.</param> /// <param name="audience">Patient or Healthcare provider</param> /// <param name="language">The language in which the details needs to be fetched</param> /// <param name="id">The Id for the term</param> /// <param name="requestedFields"> The list of fields that needs to be sent in the response</param> /// <returns>An object of GlossaryTerm</returns> /// </summary> public async Task <GlossaryTerm> GetById(string dictionary, AudienceType audience, string language, long id, string[] requestedFields) { IGetResponse <GlossaryTerm> response = null; try { string idValue = id + "_" + dictionary + "_" + language + "_" + audience.ToString().ToLower(); response = await _elasticClient.GetAsync <GlossaryTerm>(new DocumentPath <GlossaryTerm>(idValue), g => g.Index( this._apiOptions.AliasName ).Type("terms")); } catch (Exception ex) { String msg = String.Format("Could not search dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id); _logger.LogError(msg, ex); throw new APIErrorException(500, msg); } if (!response.IsValid) { String msg = String.Format("Invalid response when searching for dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id); _logger.LogError(msg); throw new APIErrorException(500, msg); } if (null == response.Source) { string msg = String.Format("Empty response when searching for dictionary '{0}', audience '{1}', language '{2}' and id '{3}.", dictionary, audience, language, id); _logger.LogError(msg); throw new APIErrorException(200, msg); } return(response.Source); }
/// <summary> /// Get a single document by it's Id. Uses the clients default index /// </summary> /// <typeparam name="T">Type of Document to return</typeparam> /// <param name="id">Id of document</param> /// <returns><see cref="T"/>T</returns> public T Get <T>(string id) where T : class { int retryCount = 0; Exception lastException = null; while (retryCount < MaxRetry) { try { IGetRequest getRequest = new GetRequest <T>(_client.ConnectionSettings.DefaultIndex, typeof(T).Name, new Id(id)); IGetResponse <T> searchResponse = _client.Get <T>(getRequest); if (!searchResponse.IsValid) { throw new ElasticSearchServerException(searchResponse.ServerError.Error); } return(searchResponse.Source); } catch (WebException wex) { lastException = wex; } catch (Exception ex) { lastException = ex; } retryCount++; Thread.Sleep(500); } throw new ElasticSearchException("There was an error occured while performing a search", lastException); }
protected override void ExpectResponse(IGetResponse <CommitActivity> response) { response.Source.Should().NotBeNull(); response.Source.Id.Should().Be(CommitActivityId); response.Parent.Should().NotBeNullOrEmpty(); response.Routing.Should().NotBeNullOrEmpty(); }
protected override void ExpectResponse(IGetResponse <Project> response) { response.Found.Should().BeFalse(); response.Index.Should().Be("project"); response.Type.Should().Be("project"); response.Id.Should().Be(this.CallIsolatedValue); }
private void DefaultAssertations(IGetResponse<ElasticSearchProject> result) { result.IsValid.Should().BeTrue(); result.Id.Should().Be("1"); result.Index.Should().Be("nest_test_data"); result.Type.Should().Be("elasticsearchprojects"); result.Version.Should().Be("1"); }
private void DefaultAssertations(IGetResponse <ElasticSearchProject> result) { result.IsValid.Should().BeTrue(); result.Id.Should().Be("1"); result.Index.Should().Be(ElasticsearchConfiguration.DefaultIndex); result.Type.Should().Be("elasticsearchprojects"); result.Version.Should().Be("1"); result.Exists.Should().BeTrue(); }
private static IGetResponse <Album> Get_BadIndex(ElasticClient client) { IGetResponse <Album> response = client.Get <Album>(g => g .Index("foo") .Id(59) ); return(response); }
private static IGetResponse <Album> Get_BadId(ElasticClient client) { IGetResponse <Album> response = client.Get <Album>(g => g .Index("rolling-stone-500") .Id(501) ); return(response); }
protected override void ExpectResponse(IGetResponse <CommitActivity> response) { response.Source.Should().NotBeNull(); response.Source.Id.Should().Be(CommitActivityId); response.Routing.Should().NotBeNullOrEmpty(); #pragma warning disable 618 response.Parent.Should().BeNullOrEmpty(); #pragma warning restore 618 }
/// <summary> /// Gets the best bets category list asynchronously /// </summary> /// <param name="collection">The collection to use. This will be 'live' or 'preview'.</param> /// <param name="categoryID"></param> /// <returns></returns> public async Task <IBestBetDisplay> GetBestBetForDisplay(string collection, string categoryID) { // Set up alias string alias = (collection == "preview") ? this._bestbetsConfig.PreviewAliasName : this._bestbetsConfig.LiveAliasName; // Validate category ID isn't null and is a number if (string.IsNullOrWhiteSpace(categoryID)) { throw new ArgumentNullException("The resource identifier is null or an empty string."); } int catID; bool isValid = int.TryParse(categoryID, out catID); BestBetsCategoryDisplay result = null; if (isValid) { IGetResponse <BestBetsCategoryDisplay> response = null; try { // Fetch the category display with the given ID from the API. response = await _elasticClient.GetAsync <BestBetsCategoryDisplay>(new GetRequest(alias, "categorydisplay", categoryID)); } catch (Exception ex) { _logger.LogError("Could not fetch category ID " + categoryID, ex); throw new APIErrorException(500, "Could not fetch category ID " + categoryID); } // If the API's response isn't valid, throw an error and return 500 status code. if (!response.IsValid) { throw new APIErrorException(500, "Errors occurred."); } // If the API finds the category ID, return the resource. if (response.Found && response.IsValid) { result = response.Source; } // If the API cannot find the category ID, throw an error and return 404 status code. else if (!response.Found && response.IsValid) { throw new APIErrorException(404, "Category not found."); } } else { // Throw an exception if the given ID is invalid (not an int). throw new APIErrorException(400, "The category identifier is invalid."); } return(result); }
private void DefaultAssertations(IGetResponse<ElasticsearchProject> result) { result.IsValid.Should().BeTrue(); result.Id.Should().Be("1"); result.Index.Should().Be(ElasticsearchConfiguration.DefaultIndex); result.Type.Should().Be("elasticsearchprojects"); result.Version.Should().Be("1"); result.Found.Should().BeTrue(); }
public virtual TModel GetById(Guid id) { return(base.ExecuteFunction("GetById", delegate() { ElasticClient client = ClientFactory.CreateClient(); IGetResponse <TModel> result = client.Get <TModel>(id.ToString(), ClientFactory.IndexName, this.DocumentType); return result.Source; })); }
/// <summary> /// Asynchronously gets a resource from the API via its ID. /// </summary> /// <param name="id">The ID of the resource</param> /// <returns>The resource</returns> public async Task <Resource> GetAsync(string id) { Resource resResult = null; // If the given ID is null or empty, throw an exception. if (string.IsNullOrWhiteSpace(id)) { throw new ArgumentNullException("The resource identifier is null or an empty string."); } // Validate if given ID is correctly formatted as an int. int resID; bool validID = int.TryParse(id, out resID); if (validID) { IGetResponse <Resource> response = null; try { // Fetch the resource with the given ID from the API. response = await _elasticClient.GetAsync <Resource>(new GetRequest(this._apiOptions.AliasName, "resource", resID)); } catch (Exception ex) { // Throw an exception if an error occurs. _logger.LogError("Could not fetch resource ID " + resID, ex); throw new APIErrorException(500, "Could not fetch resource ID " + resID); } // If the API's response isn't valid, throw an error and return 500 status code. if (!response.IsValid) { throw new APIErrorException(500, "Errors occurred."); } // If the API finds the resource, return the resource. if (response.Found && response.IsValid) { resResult = response.Source; } // If the API cannot find the resource, throw an error and return 404 status code. else if (!response.Found && response.IsValid) { throw new APIErrorException(404, "Resource not found."); } } else { // Throw an exception if the given ID is invalid (not an int). throw new APIErrorException(400, "The resource identifier is invalid."); } return(resResult); }
/// <summary> /// 查询一条文档 /// </summary> /// <typeparam name="T">文档类型</typeparam> /// <param name="id">文档id</param> /// <param name="index">文档所在库</param> /// <returns>返回该文档</returns> public T Query <T>(long id, string index = null) where T : class { IGetResponse <T> response = _builder?.Client.Get <T>(id, x => x.Type(typeof(T).SearchName()).Index(index ?? _defaultIndex)); var t = response?.Source; if (t == null) { if (_logger != null) { _logger.LogInformation(response.ApiCall.DebugInformation); } } return(t); }
//private readonly IEnumerable<string> _wikiPages; //private readonly string _wikiUrl1; //private readonly string _wikiUrl2; public WikiService(IConfiguration configuration, IIataRepository iata, IGetResponse response, IOptions <WikiConfiguration> wikiConf) { _configuration = configuration; _iata = iata; _response = response; _wikiConf = wikiConf.Value; //_wikiPages = _configuration.GetSection("Wiki:Pages").GetChildren() // .ToArray().Select(v => v.Value); //_wikiUrl1 = _configuration.GetValue<string>("Wiki:Url1"); //_wikiUrl2 = _configuration.GetValue<string>("Wiki:Url2"); }
public void PruneEntries(IGetResponse g) { var entries = g .Get(new LWWDictionaryKey <string, DeduplicationState>( this._receiver.ReplicatorKey)); var toPrune = entries.Where(r => r.Value?.PruneAfter != null && r.Value.PruneAfter <= DateTime.Now); foreach (var deduplicationState in toPrune) { PurgeKey(deduplicationState.Key); } }
protected override IElasticClient CreateElasticClient() { this.testResponse = Substitute.For <IGetResponse <PublicScheme> >(); var realElastic = base.CreateElasticClient(); var stubElastic = Substitute.For <IElasticClient>(); stubElastic.GetAsync <PublicScheme>(Arg.Any <DocumentPath <PublicScheme> >()) .Returns(x => { realElastic.Get <PublicScheme>(x.Arg <DocumentPath <PublicScheme> >()); return(this.testResponse); }); return(stubElastic); }
/// <summary> /// Get document by id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <param name="indexName"></param> /// <param name="typeName"></param> /// <returns></returns> public T Find <T>(string id, string indexName, string typeName) where T : class { if (!string.IsNullOrEmpty(indexName)) { indexName = indexName.ToLower(); } if (!string.IsNullOrEmpty(typeName)) { typeName = typeName.ToLower(); } IGetRequest getRequest = new GetRequest(indexName, typeName, id); IGetResponse <T> result = _client.Get <T>(getRequest); return(result.Source); }
public static FindHit <T> ToFindHit <T>(this IGetResponse <T> hit) where T : class { var versionedDoc = hit.Source as IVersioned; if (versionedDoc != null && hit.Version != null) { versionedDoc.Version = Int64.Parse(hit.Version); } var data = new DataDictionary { { ElasticDataKeys.Index, hit.Index }, { ElasticDataKeys.IndexType, hit.Type } }; return(new FindHit <T>(hit.Id, hit.Source, 0, versionedDoc?.Version ?? null, data)); }
public async Task <T> GetByIdAsync(long id) { List <T> entities = new List <T>(); IGetResponse <T> result = await this._esClient.GetAsync <T>(id); if (!result.IsValid) { this._logger.LogError(result.OriginalException, $"Error in getting entity: {id} of type {this._entityType} to index {this._entityIndex}", new[] { result }); throw result.OriginalException; } this._logger.LogTrace($"Retrieved entity {result.Id} from type {this._entityType} - index {this._entityIndex}.", new[] { result }); return(result.Source); }
public async Task <Employee> ExecuteQueryAsync(EmployeeGetQuery query, CancellationToken cancellationToken) { ReadModelDescription readModelDescription = _readModelDescriptionProvider.GetReadModelDescription <EmployeeReadModel>(); string indexName = "eventflow-" + readModelDescription.IndexName.Value; await _elasticClient.Indices.FlushAsync(indexName, d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)), cancellationToken) .ConfigureAwait(false); await _elasticClient.Indices.RefreshAsync(indexName, d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)), cancellationToken) .ConfigureAwait(false); IGetResponse <EmployeeReadModel> searchResponse = await _elasticClient.GetAsync <EmployeeReadModel>(query.EmployeeId.Value, d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)).Index(readModelDescription.IndexName.Value), cancellationToken) .ConfigureAwait(false); return(searchResponse.Source.ToEmployee()); }
private CacheItem CheckExpired(IGetResponse <CacheItem> response) { if (response.Source == null || response.Source.ExpiresAtTime < _systemClock.UtcNow) { return(null); } else { var cacheItem = response.Source; var expires = cacheItem.ExpiresAtTime; UpdateExpireTime(cacheItem); if (expires != cacheItem.ExpiresAtTime) { _client.Index <CacheItem>(cacheItem, i => i.Id(cacheItem.Id).Refresh(_refresh)); } return(cacheItem); } }
public async Task <Company> ExecuteQueryAsync(CompanyGetQuery query, CancellationToken cancellationToken) { ReadModelDescription readModelDescription = _readModelDescriptionProvider.GetReadModelDescription <CompanyReadModel>(); string indexName = readModelDescription.IndexName.Value; await _elasticClient.FlushAsync(indexName, d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)), cancellationToken) .ConfigureAwait(false); await _elasticClient.RefreshAsync(indexName, d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)), cancellationToken) .ConfigureAwait(false); IGetResponse <CompanyReadModel> response = await _elasticClient.GetAsync <CompanyReadModel>( query.CompanyId.Value.ToString(), d => d.RequestConfiguration(c => c.AllowedStatusCodes((int)HttpStatusCode.NotFound)) .Index(indexName), cancellationToken) .ConfigureAwait(false); return(response.Source.ToCompany()); }
public static void GetAlbum(string url) { var uri = new Uri(url); var config = new ConnectionSettings(uri); config.ExposeRawResponse(true); var client = new ElasticClient(config); IGetResponse <Album> response = Get_InlineFunc(client); ExamineResponse(response); IGetResponse <Album> response2 = Get_BadId(client); ExamineResponse(response2); IGetResponse <Album> response3 = Get_BadIndex(client); ExamineResponse(response3); }
public async Task <DataAccessResponse <Friend> > Get(string id) { DataAccessResponse <Friend> response = new DataAccessResponse <Friend>(); IGetResponse <Friend> getResponse = await _esClient.GetAsync <Friend>(id); if (!getResponse.Found) { return(response.NotFound()); } if (!getResponse.IsValid) { return(response.InternalServerError()); } Friend friend = getResponse.Source; friend.Id = getResponse.Id; return(response.Ok(friend));; }
public PhanQuyen GetById(string id, string[] fields = null) { try { if (fields != null && fields.Length > 0) { IGetResponse <PhanQuyen> res = client.Get <PhanQuyen>(id, g => g.SourceIncludes(fields)); if (res != null && res.IsValid) { var obj = res.Source; obj.id = id; return(obj); } } else { return(client.Get <PhanQuyen>(id).Source); } } catch { } return(new PhanQuyen()); }
protected override void ExpectResponse(IGetResponse <Project> response) { response.Source.Should().NotBeNull(); response.Source.Name.Should().Be(ProjectId); }