public async Task QueryStatic() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); SearchIndexClient client = resources.GetQueryClient(); #region Snippet:Azure_Search_Tests_Samples_Readme_StaticQuery //@@ SearchResults<Hotel> response = client.Search<Hotel>("luxury"); /*@@*/ SearchResults <Hotel> response = await client.SearchAsync <Hotel>("luxury"); //@@ foreach (SearchResult<Hotel> result in response.GetResults()) /*@@*/ await foreach (SearchResult <Hotel> result in response.GetResultsAsync()) { Hotel doc = result.Document; Console.WriteLine($"{doc.Id}: {doc.Name}"); } #endregion Snippet:Azure_Search_Tests_Samples_Readme_StaticQuery #region Snippet:Azure_Search_Tests_Samples_Readme_StaticQueryAsync //@@SearchResults<Hotel> response = await client.SearchAsync<Hotel>("luxury"); /*@@*/ response = await client.SearchAsync <Hotel>("luxury"); await foreach (SearchResult <Hotel> result in response.GetResultsAsync()) { Hotel doc = result.Document; Console.WriteLine($"{doc.Id}: {doc.Name}"); } #endregion Snippet:Azure_Search_Tests_Samples_Readme_StaticQueryAsync }
public async Task CanContinueWithoutSize() { const int size = 167; await using SearchResources resources = await CreateLargeHotelsIndexAsync(size); SearchIndexClient client = resources.GetQueryClient(); Response <SearchResults <SearchDocument> > response = await client.SearchAsync( "*", new SearchOptions { OrderBy = new[] { "hotelId asc" }, Select = new[] { "hotelId" } }); List <string> ids = new List <string>(); // Get the first page Page <SearchResult <SearchDocument> > page = await response.Value.GetResultsAsync().AsPages().FirstAsync(); Assert.LessOrEqual(page.Values.Count, 50); ids.AddRange(page.Values.Select(d => (string)d.Document["hotelId"])); Assert.NotNull(page.ContinuationToken); // Get the second page response = await client.SearchAsync(null, new SearchOptions(page.ContinuationToken)); page = await response.Value.GetResultsAsync().AsPages().FirstAsync(); Assert.LessOrEqual(page.Values.Count, 50); ids.AddRange(page.Values.Select(d => (string)d.Document["hotelId"])); Assert.NotNull(page.ContinuationToken); // Get the third page response = await client.SearchAsync(null, new SearchOptions(page.ContinuationToken)); page = await response.Value.GetResultsAsync().AsPages().FirstAsync(); Assert.LessOrEqual(page.Values.Count, 50); ids.AddRange(page.Values.Select(d => (string)d.Document["hotelId"])); Assert.NotNull(page.ContinuationToken); // Get the final page response = await client.SearchAsync(null, new SearchOptions(page.ContinuationToken)); page = await response.Value.GetResultsAsync().AsPages().FirstAsync(); Assert.LessOrEqual(page.Values.Count, 50); ids.AddRange(page.Values.Select(d => (string)d.Document["hotelId"])); Assert.IsNull(page.ContinuationToken); // Verify we saw everything CollectionAssert.AreEquivalent( Enumerable.Range(1, size).Select(i => i.ToString()), ids); }
public async Task CreateAndQuery() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString()); Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey); string indexName = resources.IndexName; #region Snippet:Azure_Search_Tests_Samples_Readme_Client // Get the service endpoint and API key from the environment Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT")); string key = Environment.GetEnvironmentVariable("SEARCH_API_KEY"); //@@ string indexName = "hotels"; // Create a client AzureKeyCredential credential = new AzureKeyCredential(key); SearchIndexClient client = new SearchIndexClient(endpoint, indexName, credential); /*@@*/ client = InstrumentClient(new SearchIndexClient(endpoint, indexName, credential, GetSearchClientOptions())); #endregion Snippet:Azure_Search_Tests_Samples_Readme_Client #region Snippet:Azure_Search_Tests_Samples_Readme_Dict //@@ SearchResults<SearchDocument> response = client.Search("luxury"); /*@@*/ SearchResults <SearchDocument> response = await client.SearchAsync("luxury"); //@@ foreach (SearchResult<SearchDocument> result in response.GetResults()) /*@@*/ await foreach (SearchResult <SearchDocument> result in response.GetResultsAsync()) { SearchDocument doc = result.Document; string id = (string)doc["hotelId"]; string name = (string)doc["hotelName"]; Console.WriteLine("{id}: {name}"); } #endregion Snippet:Azure_Search_Tests_Samples_Readme_Dict #region Snippet:Azure_Search_Tests_Samples_Readme_Dynamic //@@ SearchResults<SearchDocument> response = client.Search("luxury"); /*@@*/ response = await client.SearchAsync("luxury"); //@@ foreach (SearchResult<SearchDocument> result in response.GetResults()) /*@@*/ await foreach (SearchResult <SearchDocument> result in response.GetResultsAsync()) { dynamic doc = result.Document; string id = doc.hotelId; string name = doc.hotelName; Console.WriteLine("{id}: {name}"); } #endregion Snippet:Azure_Search_Tests_Samples_Readme_Dynamic }
public async Task FirstQuery() { #region Snippet:Azure_Search_Tests_Samples_Readme_FirstQuery // We'll connect to the Azure Cognitive Search public sandbox and send a // query to its "nycjobs" index built from a public dataset of available jobs // in New York. string serviceName = "azs-playground"; string indexName = "nycjobs"; string apiKey = "252044BE3886FE4A8E3BAA4F595114BB"; // Create a SearchIndexClient to send queries Uri serviceEndpoint = new Uri($"https://{serviceName}.search.windows.net/"); AzureKeyCredential credential = new AzureKeyCredential(apiKey); SearchIndexClient client = new SearchIndexClient(serviceEndpoint, indexName, credential); // Let's get the top 5 jobs related to Microsoft //@@ SearchResults<SearchDocument> response = client.Search("Microsoft", new SearchOptions { Size = 5 }); //@@ foreach (SearchResult<SearchDocument> result in response.GetResults()) /*@@*/ SearchResults <SearchDocument> response = await client.SearchAsync("Microsoft", new SearchOptions { Size = 5 }); /*@@*/ await foreach (SearchResult <SearchDocument> result in response.GetResultsAsync()) { // Print out the title and job description (we'll see below how to // use C# objects to make accessing these fields much easier) string title = (string)result.Document["business_title"]; string description = (string)result.Document["job_description"]; Console.WriteLine($"{title}\n{description}\n"); } #endregion Snippet:Azure_Search_Tests_Samples_Readme_FirstQuery }
public async Task ThrowsWhenRequestIsMalformed() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); SearchIndexClient client = resources.GetQueryClient(); SearchOptions invalidOptions = new SearchOptions { Filter = "This is not a valid filter." }; RequestFailedException ex = await CatchAsync <RequestFailedException>( async() => await client.SearchAsync("*", invalidOptions)); Assert.AreEqual(400, ex.Status); StringAssert.StartsWith("Invalid expression: Syntax error at position 7 in 'This is not a valid filter.'", ex.Message); }
public async Task RegexSpecialCharsUnescapedThrows() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); SearchIndexClient client = resources.GetQueryClient(); RequestFailedException ex = await CatchAsync <RequestFailedException>( async() => await client.SearchAsync( @"/.*/.*/", new SearchOptions { QueryType = SearchQueryType.Full })); Assert.AreEqual(400, ex.Status); StringAssert.StartsWith("Failed to parse query string at line 1, column 8.", ex.Message); }
/// <summary> /// Get the next (server-side) page of results. /// </summary> /// <param name="async"> /// Whether to execute synchronously or asynchronously. /// </param> /// <param name="cancellationToken"> /// Optional <see cref="CancellationToken"/> to propagate notifications /// that the operation should be canceled. /// </param> /// <returns>The next page of SearchResults.</returns> internal async Task <SearchResults <T> > GetNextPageAsync(bool async, CancellationToken cancellationToken) { SearchResults <T> next = null; if (_indexClient != null && NextOptions != null) { next = async ? await _indexClient.SearchAsync <T>( NextOptions.SearchText, NextOptions, cancellationToken) .ConfigureAwait(false) : _indexClient.Search <T>( NextOptions.SearchText, NextOptions, cancellationToken); } return(next); }
public async Task Options() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); SearchIndexClient client = resources.GetQueryClient(); #region Snippet:Azure_Search_Tests_Samples_Readme_Options int stars = 4; SearchOptions options = new SearchOptions { // Filter to only ratings greater than or equal our preference Filter = SearchFilter.Create($"rating ge {stars}"), Size = 5, // Take only 5 results OrderBy = new[] { "rating desc" } // Sort by rating from high to low }; //@@ SearchResults<Hotel> response = client.Search<Hotel>("luxury", options); // ... #endregion Snippet:Azure_Search_Tests_Samples_Readme_Options await client.SearchAsync <Hotel>("luxury", options); }
public async Task StaticDocuments() { await using SearchResources resources = await SearchResources.GetSharedHotelsIndexAsync(this); SearchIndexClient client = resources.GetQueryClient(); SearchResults <Hotel> response = await client.SearchAsync <Hotel>("*"); Assert.IsNull(response.TotalCount); Assert.IsNull(response.Coverage); Assert.IsNull(response.Facets); List <SearchResult <Hotel> > docs = await response.GetResultsAsync().ToListAsync(); Assert.AreEqual(SearchResources.TestDocuments.Length, docs.Count); for (int i = 0; i < docs.Count; i++) { Assert.AreEqual(1, docs[i].Score); Assert.IsNull(docs[i].Highlights); Assert.AreEqual(SearchResources.TestDocuments[i], docs[i].Document); } }