public DocumentSearchClient(IConfiguration configuration, bool videoIndexerTimeRefs = false) { try { _configuration = configuration; searchServiceName = configuration.GetSection("SearchServiceName")?.Value; apiKey = configuration.GetSection("SearchApiKey")?.Value; IndexName = videoIndexerTimeRefs ? configuration.GetSection("SearchIndexNameVideoIndexerTimeRef")?.Value : configuration.GetSection("SearchIndexName")?.Value; IndexerName = configuration.GetSection("SearchIndexerName")?.Value; idField = configuration.GetSection("KeyField")?.Value; telemetryClient.InstrumentationKey = configuration.GetSection("InstrumentationKey")?.Value; // Options used to get a search id for reporting SearchClientOptions clientOptions = new SearchClientOptions(); clientOptions.AddPolicy(new SearchIdPipelinePolicy(), HttpPipelinePosition.PerCall); // Create an HTTP reference to the catalog index _searchIndexClient = new SearchIndexClient(new Uri($"https://{searchServiceName}.search.windows.net/"), new AzureKeyCredential(apiKey), options: clientOptions); _searchClient = _searchIndexClient.GetSearchClient(IndexName); Schema = new SearchSchema().AddFields(_searchIndexClient.GetIndex(IndexName).Value.Fields); Model = new SearchModel(Schema); _isPathBase64Encoded = (configuration.GetSection("IsPathBase64Encoded")?.Value == "True"); } catch (Exception e) { // If you get an exception here, most likely you have not set your // credentials correctly in appsettings.json throw new ArgumentException(e.Message.ToString()); } }
/// <summary> /// Queries an index of mountains. /// </summary> /// <param name="endpoint">The Search service URI.</param> /// <param name="key">The query key for the Search service.</param> /// <param name="query">Keywords to query. The default is "*".</param> /// <returns></returns> private static async Task Main(Uri endpoint, string key, string query = "*") { using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (sender, args) => { cts.Cancel(); args.Cancel = true; }; var credential = new AzureKeyCredential(key); var options = new SearchClientOptions { Serializer = new NewtonsoftJsonObjectSerializer( new JsonSerializerSettings { Converters = { new NewtonsoftJsonMicrosoftSpatialGeoJsonConverter(), }, } ), }; var client = new SearchClient(endpoint, Mountain.IndexName, credential, options); var results = await client.SearchAsync <Mountain>(query); await foreach (var result in results.Value.GetResultsAsync()) { var mountain = result.Document; Console.WriteLine("https://www.bing.com/maps?cp={0}~{1}&sp=point.{0}_{1}_{2}", mountain.Summit.Latitude, mountain.Summit.Longitude, Uri.EscapeUriString(mountain.Name)); } }
public void DiagnosticsAreUnique() { // Make sure we're not repeating Header/Query names already defined // in the base ClientOptions SearchClientOptions options = new SearchClientOptions(); Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedHeaderNames)); Assert.IsEmpty(GetDuplicates(options.Diagnostics.LoggedQueryParameters));
public IActionResult Search(SearchClientOptions options) { var result = clientService_ .SearchClient(options) .Data.ToList(); return(Json(result)); }
public void SearchSample() { // cspell:word Aragorn Sauron's MockResponse response = new MockResponse(200); response.SetContent(@"{ ""value"": [ { ""@search.score"": 1.0, ""uuid"": ""efe8857f-1d74-41e2-9ff1-4943a9ad69d5"", ""title"": ""The Lord of the Rings: The Return of the King"", ""description"": ""Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring."", ""rating"": 9.1 } ] }"); Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", "https://sample.search.windows.net"); Environment.SetEnvironmentVariable("SEARCH_API_KEY", "sample"); #region Snippet:Microsoft_Azure_Core_NewtonsoftJson_Samples_Readme_SearchSample // Get the Azure Cognitive Search endpoint and read-only API key. Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")); AzureKeyCredential credential = new AzureKeyCredential(Environment.GetEnvironmentVariable("SEARCH_API_KEY")); // Create serializer options with default converters for Azure SDKs. JsonSerializerSettings serializerSettings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings(); // Serialize property names using camelCase by default. serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); SearchClientOptions clientOptions = new SearchClientOptions { #if !SNIPPET Transport = new MockTransport(response), #endif Serializer = new NewtonsoftJsonObjectSerializer(serializerSettings) }; SearchClient client = new SearchClient(endpoint, "movies", credential, clientOptions); Response <SearchResults <Movie> > results = client.Search <Movie>("Return of the King"); foreach (SearchResult <Movie> result in results.Value.GetResults()) { Movie movie = result.Document; Console.WriteLine(movie.Title); Console.WriteLine(movie.Description); Console.WriteLine($"Rating: {movie.Rating}\n"); } #endregion Snippet:Microsoft_Azure_Core_NewtonsoftJson_Samples_Readme_SearchSample Movie _movie = results.Value.GetResults().Single().Document; Assert.AreEqual("efe8857f-1d74-41e2-9ff1-4943a9ad69d5", _movie.Id); Assert.AreEqual("The Lord of the Rings: The Return of the King", _movie.Title); Assert.AreEqual("Gandalf and Aragorn lead the World of Men against Sauron's army to draw his gaze from Frodo and Sam as they approach Mount Doom with the One Ring.", _movie.Description); Assert.AreEqual(9.1, _movie.Rating, 0.01); }
/// <summary> /// Create default client options for testing (and instrument them with /// the recording transports). /// </summary> /// <param name="options">Optional client options.</param> /// <returns>SearchClientOptions for testing</returns> public SearchClientOptions GetSearchClientOptions(SearchClientOptions options = null) { options ??= new SearchClientOptions(ServiceVersion); options.Diagnostics.IsLoggingEnabled = true; options.Retry.Mode = RetryMode.Exponential; options.Retry.MaxRetries = 10; options.Retry.Delay = TimeSpan.FromSeconds(Mode == RecordedTestMode.Playback ? 0.01 : 1); options.Retry.MaxDelay = TimeSpan.FromSeconds(Mode == RecordedTestMode.Playback ? 0.1 : 600); options.Transport = new HttpClientTransport(s_httpClient); return(Recording.InstrumentClientOptions(options)); }
public ApiResult <Client> GetClientById(int?id) { if (id == null) { return(ApiResult <Client> .Failed(StatusCode.BadRequest, "Id is empty")); } var options = new SearchClientOptions() { ClientId = id.Value }; return(ApiResult <Client> .Successful(SearchClient(options).Data.SingleOrDefault())); }
public static IServiceCollection AddAzureSearchClient <TResult>( this IServiceCollection services, Uri endpoint, string key, string indexName, Action <SearchClientOptions> configureOptions = null) { var options = new SearchClientOptions(); configureOptions?.Invoke(options); return(services.AddSingleton <ISearchClient <TResult> >(s => new AzureSearchClient <TResult>( new SearchClient(endpoint, indexName, new AzureKeyCredential(key), options)))); }
public ApiResult <IQueryable <Client> > SearchClient(SearchClientOptions options) { if (options == null) { return(ApiResult <IQueryable <Client> > .Failed(StatusCode.BadRequest, "Null options")); } var query = context_ .Set <Client>() .AsQueryable(); if (options.ClientId != null) { query = query.Where(c => c.ClientId == options.ClientId); } if (!string.IsNullOrWhiteSpace(options.Firstname)) { query = query.Where(c => c.Firstname == options.Firstname); } if (!string.IsNullOrWhiteSpace(options.Lastname)) { query = query.Where(c => c.Lastname == options.Lastname); } if (!string.IsNullOrWhiteSpace(options.Email)) { query = query.Where(c => c.Email == options.Email); } if (!string.IsNullOrWhiteSpace(options.Phone)) { query = query.Where(c => c.Phone == options.Phone); } if (options.CreatedFrom != null) { query = query.Where(c => c.Created >= options.CreatedFrom); } if (options.CreatedTo != null) { query = query.Where(c => c.Created < options.CreatedTo); } return(ApiResult <IQueryable <Client> > .Successful(query.Take(500))); }
public async Task IndexSharesPipeline() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); TestPipelinePolicy custom = new TestPipelinePolicy(); Assert.AreEqual(0, custom.RequestCount); SearchClientOptions options = new SearchClientOptions(ServiceVersion); options.AddPolicy(custom, HttpPipelinePosition.PerCall); SearchServiceClient client = resources.GetServiceClient(options); SearchIndexClient index = client.GetSearchIndexClient(resources.IndexName); _ = await index.GetDocumentCountAsync(); Assert.AreEqual(1, custom.RequestCount); }
public void DefaultSerializerSettings() { #region Snippet:Microsoft_Azure_Core_NewtonsoftJson_Samples_Readme_DefaultSerializerSettings JsonSerializerSettings serializerSettings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings(); // Serialize property names using camelCase by default. serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // Add converters as needed, for example, to convert movie genres to an enum. serializerSettings.Converters.Add(new StringEnumConverter()); SearchClientOptions clientOptions = new SearchClientOptions { Serializer = new NewtonsoftJsonObjectSerializer(serializerSettings) }; #endregion Snippet:Microsoft_Azure_Core_NewtonsoftJson_Samples_Readme_DefaultSerializerSettings Assert.AreEqual(2, serializerSettings.Converters.Count); Assert.That(serializerSettings.Converters, Has.Some.TypeOf(typeof(NewtonsoftJsonETagConverter))); Assert.That(serializerSettings.Converters, Has.Some.TypeOf(typeof(StringEnumConverter))); }
public void SearchSample() { MockResponse response = new MockResponse(200); response.SetContent(@"{ ""value"": [ { ""@search.score"": 1.0, ""id"": ""1"", ""name"": ""Mount Rainier"", ""summit"": { ""type"": ""Point"", ""coordinates"": [ -121.76044, 46.85287 ] } } ] }"); Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", "https://sample.search.windows.net"); Environment.SetEnvironmentVariable("SEARCH_API_KEY", "sample"); #region Snippet:Microsoft_Azure_Core_Spatial_NewtonsoftJson_Samples_Readme_SearchSample // Get the Azure Cognitive Search endpoint and read-only API key. Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")); AzureKeyCredential credential = new AzureKeyCredential(Environment.GetEnvironmentVariable("SEARCH_API_KEY")); // Create serializer options with our converter to deserialize geographic points. JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), Converters = { new NewtonsoftJsonMicrosoftSpatialGeoJsonConverter() } }; SearchClientOptions clientOptions = new SearchClientOptions { /*@@*/ Transport = new MockTransport(response), Serializer = new NewtonsoftJsonObjectSerializer(serializerSettings) }; SearchClient client = new SearchClient(endpoint, "mountains", credential, clientOptions); Response <SearchResults <Mountain> > results = client.Search <Mountain>("Rainier"); foreach (SearchResult <Mountain> result in results.Value.GetResults()) { Mountain mountain = result.Document; Console.WriteLine("https://www.bing.com/maps?cp={0}~{1}&sp=point.{0}_{1}_{2}", mountain.Summit.Latitude, mountain.Summit.Longitude, Uri.EscapeUriString(mountain.Name)); } #endregion Snippet:Microsoft_Azure_Core_Spatial_NewtonsoftJson_Samples_Readme_SearchSample Mountain _mountain = results.Value.GetResults().Single().Document; Assert.AreEqual("Mount Rainier", _mountain.Name); Assert.AreEqual(-121.76044, _mountain.Summit.Longitude); Assert.AreEqual(46.85287, _mountain.Summit.Latitude); }
static void Main(string[] args) { string serviceName = "lynx-searchengine-jsancho"; string indexName = "hotels-quickstart-v11"; string apiKey = "6C88A8613367F73135756A4CCFE1C24C"; // Create a SearchIndexClient to send create/delete index commands Uri serviceEndpoint = new Uri($"https://{serviceName}.search.windows.net/"); AzureKeyCredential credential = new AzureKeyCredential(apiKey); SearchIndexClient idxclient = new SearchIndexClient(serviceEndpoint, credential); // Create a SearchClient to load and query documents SearchClient srchclient = new SearchClient(serviceEndpoint, indexName, credential); // Delete index if it exists Console.WriteLine("{0}", "Deleting index...\n"); DeleteIndexIfExists(indexName, idxclient); var searchClientOptions = new SearchClientOptions { Serializer = new JsonObjectSerializer( new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) }; var builder = new FieldBuilder { Serializer = searchClientOptions.Serializer }; var index = new SearchIndex(indexName) { Fields = builder.Build(typeof(Hotel)) }; Console.WriteLine("{0}", "Creating index...\n"); idxclient.CreateIndex(index); // Load documents (using a subset of fields for brevity) IndexDocumentsBatch <Hotel> batch = IndexDocumentsBatch.Create( IndexDocumentsAction.Upload(new Hotel { Id = "78", Name = "Upload Inn", Category = "hotel", Rate = 279, Updated = new DateTime(2018, 3, 1, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "54", Name = "Breakpoint by the Sea", Category = "motel", Rate = 162, Updated = new DateTime(2015, 9, 12, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "39", Name = "Debug Motel", Category = "motel", Rate = 159, Updated = new DateTime(2016, 11, 11, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "48", Name = "NuGet Hotel", Category = "hotel", Rate = 238, Updated = new DateTime(2016, 5, 30, 7, 0, 0) }), IndexDocumentsAction.Upload(new Hotel { Id = "12", Name = "Renovated Ranch", Category = "motel", Rate = 149, Updated = new DateTime(2020, 1, 24, 7, 0, 0) })); IndexDocumentsOptions idxoptions = new IndexDocumentsOptions { ThrowOnAnyError = true }; Console.WriteLine("{0}", "Loading index...\n"); srchclient.IndexDocuments(batch, idxoptions); // Wait 2 secondsfor indexing to complete before starting queries (for demo and console-app purposes only) Console.WriteLine("Waiting for indexing...\n"); System.Threading.Thread.Sleep(2000); // Call the RunQueries method to invoke a series of queries Console.WriteLine("Starting queries...\n"); RunQueries(srchclient); // End the program Console.WriteLine("{0}", "Complete. Press any key to end this program...\n"); Console.ReadKey(); }
public async Task CreateIndex() { await using SearchResources resources = SearchResources.CreateWithNoIndexes(this); Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString()); Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey); #region Snippet:Azure_Search_Tests_Sample2_FieldBuilderIgnore_CreateIndex Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")); string key = Environment.GetEnvironmentVariable("SEARCH_API_KEY"); // Define client options to use camelCase when serializing property names. SearchClientOptions options = new SearchClientOptions(ServiceVersion) { Serializer = new JsonObjectSerializer( new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) }; // Create a service client. AzureKeyCredential credential = new AzureKeyCredential(key); SearchIndexClient indexClient = new SearchIndexClient(endpoint, credential, options); #if !SNIPPET indexClient = resources.GetIndexClient(options); #endif // Create the FieldBuilder using the same serializer. FieldBuilder fieldBuilder = new FieldBuilder { Serializer = options.Serializer }; // Create the index using FieldBuilder. #if SNIPPET SearchIndex index = new SearchIndex("movies") #else SearchIndex index = new SearchIndex(Recording.Random.GetName()) #endif { Fields = fieldBuilder.Build(typeof(Movie)), Suggesters = { // Suggest query terms from the "name" field. new SearchSuggester("n", "name") } }; // Define the "genre" field as a string. SearchableField genreField = new SearchableField("genre") { AnalyzerName = LexicalAnalyzerName.Values.EnLucene, IsFacetable = true, IsFilterable = true }; index.Fields.Add(genreField); // Create the index. indexClient.CreateIndex(index); #endregion Snippet:Azure_Search_Tests_Sample2_FieldBuilderIgnore_CreateIndex // Make sure the index is removed. resources.IndexName = index.Name; #region Snippet:Azure_Search_Tests_Sample2_FieldBuilderIgnore_UploadDocument Movie movie = new Movie { Id = Guid.NewGuid().ToString("n"), Name = "The Lord of the Rings: The Return of the King", Genre = MovieGenre.Fantasy, Year = 2003, Rating = 9.1 }; // Add a movie to the index. SearchClient searchClient = indexClient.GetSearchClient(index.Name); searchClient.UploadDocuments(new[] { movie }); #endregion Snippet:Azure_Search_Tests_Sample2_FieldBuilderIgnore_UploadDocument }
public BatchingSearchClient(Uri endpoint, string indexName, AzureKeyCredential credential, SearchClientOptions options) : base(endpoint, indexName, credential, options) { }