public async Task <List <string> > SuggestEvents(string searchText, int take, string[] searchFields) { var indexClientProduktionsunderlag = _searchServiceClient.Indexes.GetClient(INDEX_EVENTS); var sp = new SuggestParameters { Top = take }; //Om sökfält är angivet sök i detta, annars sök i alla som igår i suggestern och är sökbara if (searchFields != null && searchFields.Count() != 0) { sp.SearchFields = searchFields; } var response = await indexClientProduktionsunderlag.Documents.SuggestAsync <EventSearchDocument>(searchText, SUGGESTION_EVENTS, suggestParameters : sp); List <string> suggestions = new List <string>(); foreach (var result in response.Results) { suggestions.Add(result.Text); } List <string> uniqueSuggestions = suggestions.Distinct().ToList(); return(uniqueSuggestions); }
public ActionResult Both(string term) { InitSearch(); AutocompleteParameters sp1 = new AutocompleteParameters() { AutocompleteMode = AutocompleteMode.OneTermWithContext, UseFuzzyMatching = false, Top = 5, MinimumCoverage = 80 }; AutocompleteResult resp1 = _indexClient.Documents.Autocomplete(term, "sg", sp1); // Call both the suggest and autocomplete API and return results SuggestParameters sp2 = new SuggestParameters() { UseFuzzyMatching = false, Top = 5 }; DocumentSuggestResult resp2 = _indexClient.Documents.Suggest(term, "sg", sp2); //Convert the suggest query results to a list that can be displayed in the client. var result = resp1.Results.Select(x => new { label = x.Text, category = "Autocomplete" }).ToList(); result.AddRange(resp2.Results.Select(x => new { label = x.Text, category = "Suggestions" }).ToList()); return(new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = result }); }
/// <summary> /// Gets the location suggestions from the mmpk. /// </summary> /// <returns>List of location suggestions.</returns> /// <param name="userInput">User input.</param> internal async Task <IReadOnlyList <SuggestResult> > GetLocationSuggestionsAsync(string userInput) { try { var locatorInfo = this.Locator.LocatorInfo; if (locatorInfo.SupportsSuggestions) { // restrict the search to return no more than 10 suggestions var suggestParams = new SuggestParameters { MaxResults = 10 }; // get suggestions for the text provided by the user var suggestions = await this.Locator.SuggestAsync(userInput, suggestParams); return(suggestions); } } catch { return(null); } return(null); }
public DocumentSuggestResult <Document> Suggest(IndexNameType indexNameType, bool highlights, bool fuzzy, string searchText) { // Execute search based on query string try { SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 5 }; if (highlights) { sp.HighlightPreTag = "<b>"; sp.HighlightPostTag = "</b>"; } var indexClient = GetIndexClient(indexNameType); // var suggestResult = indexClient.Documents.Suggest(searchText, "sg", sp); return(indexClient.Documents.Suggest(searchText, "sg", sp)); } catch (Exception ex) { Console.WriteLine("Error querying index: {0}\r\n", ex.Message.ToString()); } return(null); }
protected void TestCanSuggestWithSelectedFields() { SearchIndexClient client = GetClientForQuery(); var suggestParameters = new SuggestParameters() { Select = new[] { "hotelName", "rating", "address/city", "rooms/type" } }; DocumentSuggestResult <Hotel> response = client.Documents.Suggest <Hotel>("secret", "sg", suggestParameters); var expectedDoc = new Hotel() { HotelName = "Secret Point Motel", Rating = 4, Address = new HotelAddress() { City = "New York" }, Rooms = new[] { new HotelRoom() { Type = "Budget Room" }, new HotelRoom() { Type = "Budget Room" } } }; Assert.Equal(1, response.Results.Count); Assert.Equal(expectedDoc, response.Results.First().Document); }
public List <string> GetSearchSuggestions(string text) { if (string.IsNullOrEmpty(text)) { return(new List <string>()); } try { bool isFuzzyEnabled = false, isHiglightsEnabled = true; // Call suggest API and return results SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = isFuzzyEnabled, Top = 5 }; //if (isHiglightsEnabled) //{ // sp.HighlightPreTag = "<b>"; // sp.HighlightPostTag = "</b>"; //} DocumentSuggestResult <Microsoft.Azure.Search.Models.Document> resp = IndexClientSearch.Documents.Suggest(text, "toksdev-suggest", sp); // Convert the suggest query results to a list that can be displayed in the client. List <string> suggestions = (resp.Results.Select(x => x.Text)).Distinct().ToList(); return(suggestions); } catch (Exception e) { return(new List <string>()); } }
public void EnsureSelectReturnsSelfWhenSelectIsPopulated() { SuggestParameters parameters = CreateTestParameters(); SuggestParameters newParameters = parameters.EnsureSelect(); Assert.Same(parameters, newParameters); }
public void CanSuggestWithSelectedFields() { Run(() => { SearchIndexClient client = Data.GetSearchIndexClientForQuery(); var suggestParameters = new SuggestParameters() { Select = new[] { "hotelName", "baseRate" } }; DocumentSuggestResponse <Hotel> response = client.Documents.Suggest <Hotel>("luxury", "sg", suggestParameters); var expectedDoc = new Hotel() { HotelName = "Fancy Stay", BaseRate = 199.0 }; Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Results); Assert.Equal(1, response.Results.Count); Assert.Equal(expectedDoc, response.Results.First().Document); }); }
public void CanConvertToPostPayload() { var parameters = new SuggestParameters() { Filter = "x eq y", HighlightPostTag = "</em>", HighlightPreTag = "<em>", MinimumCoverage = 33.3, OrderBy = new[] { "a", "b desc" }, SearchFields = new[] { "a", "b", "c" }, Select = new[] { "e", "f", "g" }, Top = 5, UseFuzzyMatching = true }; SuggestParametersPayload payload = parameters.ToPayload("find me", "mySuggester"); Assert.Equal(parameters.Filter, payload.Filter); Assert.Equal(parameters.HighlightPostTag, payload.HighlightPostTag); Assert.Equal(parameters.HighlightPreTag, payload.HighlightPreTag); Assert.Equal(parameters.MinimumCoverage, payload.MinimumCoverage); Assert.Equal(parameters.OrderBy.ToCommaSeparatedString(), payload.OrderBy); Assert.Equal("find me", payload.Search); Assert.Equal(parameters.SearchFields.ToCommaSeparatedString(), payload.SearchFields); Assert.Equal(parameters.Select.ToCommaSeparatedString(), payload.Select); Assert.Equal("mySuggester", payload.SuggesterName); Assert.Equal(parameters.Top, payload.Top); Assert.Equal(parameters.UseFuzzyMatching, payload.Fuzzy); }
public void CanUseHitHighlighting() { Run(() => { SearchIndexClient client = Data.GetSearchIndexClientForQuery(); var suggestParameters = new SuggestParameters() { HighlightPreTag = "<b>", HighlightPostTag = "</b>", Filter = "category eq 'Luxury'", Top = 1 }; DocumentSuggestResponse <Hotel> response = client.Documents.Suggest <Hotel>("hotel", "sg", suggestParameters); AssertKeySequenceEqual(response, "1"); // Note: Highlighting is not perfect due to the way Azure Search builds edge n-grams for suggestions. Assert.True( response.Results[0].Text.StartsWith("Best <b>hotel in</b> town", StringComparison.Ordinal)); }); }
protected void TestCanSuggestWithDateTimeInStaticModel() { SearchServiceClient serviceClient = Data.GetSearchServiceClient(); Index index = Book.DefineIndex(); serviceClient.Indexes.Create(index); SearchIndexClient indexClient = Data.GetSearchIndexClient(index.Name); var tolkien = new Author() { FirstName = "J.R.R.", LastName = "Tolkien" }; var doc1 = new Book() { ISBN = "123", Title = "Lord of the Rings", Author = tolkien }; var doc2 = new Book() { ISBN = "456", Title = "War and Peace", PublishDate = new DateTime(2015, 8, 18) }; var batch = IndexBatch.Upload(new[] { doc1, doc2 }); indexClient.Documents.Index(batch); SearchTestUtilities.WaitForIndexing(); var parameters = new SuggestParameters() { Select = new[] { "ISBN", "Title", "PublishDate" } }; DocumentSuggestResult <Book> response = indexClient.Documents.Suggest <Book>("War", "sg", parameters); Assert.Equal(1, response.Results.Count); Assert.Equal(doc2, response.Results[0].Document); }
protected void TestCanSuggestDynamicDocuments() { SearchIndexClient client = GetClientForQuery(); var suggestParameters = new SuggestParameters() { OrderBy = new[] { "hotelId" } }; DocumentSuggestResponse response = client.Documents.Suggest("good", "sg", suggestParameters); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Null(response.Coverage); Assert.NotNull(response.Results); Document[] expectedDocs = Data.TestDocuments .Where(h => h.HotelId == "4" || h.HotelId == "5") .OrderBy(h => h.HotelId) .Select(h => h.AsDocument()) .ToArray(); Assert.Equal(expectedDocs.Length, response.Results.Count); for (int i = 0; i < expectedDocs.Length; i++) { SearchAssert.DocumentsEqual(expectedDocs[i], response.Results[i].Document); Assert.Equal(expectedDocs[i]["description"], response.Results[i].Text); } }
protected void TestCanSuggestStaticallyTypedDocuments() { SearchIndexClient client = GetClientForQuery(); var suggestParameters = new SuggestParameters() { OrderBy = new[] { "hotelId" } }; DocumentSuggestResponse <Hotel> response = client.Documents.Suggest <Hotel>("good", "sg", suggestParameters); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Null(response.Coverage); Assert.NotNull(response.Results); IEnumerable <Hotel> expectedDocs = Data.TestDocuments.Where(h => h.HotelId == "4" || h.HotelId == "5").OrderBy(h => h.HotelId); SearchAssert.SequenceEqual( expectedDocs, response.Results.Select(r => r.Document)); SearchAssert.SequenceEqual( expectedDocs.Select(h => h.Description), response.Results.Select(r => r.Text)); }
private void TestCanSuggestWithCustomConverter <T>(Action <SearchIndexClient> customizeSettings = null) where T : CustomBook, new() { customizeSettings = customizeSettings ?? (client => { }); SearchServiceClient serviceClient = Data.GetSearchServiceClient(); Index index = Book.DefineIndex(); serviceClient.Indexes.Create(index); SearchIndexClient indexClient = Data.GetSearchIndexClient(index.Name); customizeSettings(indexClient); var doc = new T() { InternationalStandardBookNumber = "123", Name = "Lord of the Rings", AuthorName = "J.R.R. Tolkien", PublishDateTime = new DateTime(1954, 7, 29) }; var batch = IndexBatch.Upload(new[] { doc }); indexClient.Documents.Index(batch); SearchTestUtilities.WaitForIndexing(); var parameters = new SuggestParameters() { Select = new[] { "*" } }; DocumentSuggestResult <T> response = indexClient.Documents.Suggest <T>("Lord", "sg", parameters); Assert.Equal(1, response.Results.Count); Assert.Equal(doc, response.Results[0].Document); }
/// <summary> /// Gets list of suggested locations from the locator based on user input /// </summary> /// <param name="userInput">User input</param> /// <returns>List of suggestions</returns> private async Task <ObservableCollection <string> > GetLocationSuggestionsAsync(string userInput) { if (Locator?.LocatorInfo?.SupportsSuggestions ?? false && !string.IsNullOrEmpty(userInput)) { try { // restrict the search to return no more than 10 suggestions var suggestParams = new SuggestParameters { MaxResults = 10, PreferredSearchLocation = AreaOfInterest?.TargetGeometry as MapPoint, }; // get suggestions for the text provided by the user var suggestions = await Locator.SuggestAsync(userInput, suggestParams); var s = new ObservableCollection <string>(); foreach (var suggestion in suggestions) { s.Add(suggestion.Label); } return(s); } catch { // If error happens, do not show suggestions return(new ObservableCollection <string>()); } } else { return(new ObservableCollection <string>()); } }
public async Task <List <Job> > Get(string keyword) { var sp = new SuggestParameters(); sp.HighlightPreTag = "["; sp.HighlightPostTag = "]"; sp.UseFuzzyMatching = true; sp.MinimumCoverage = 50; sp.Top = 100; var indexClient = serviceClient.Indexes.GetClient("job-index"); var response = await indexClient.Documents.SuggestAsync <Job>(keyword, "suggestions", sp); var jobList = new List <Job>(); foreach (var document in response.Results) { var job = new Job { Name = document.Text, Details = document.Document.Details, Status = document.Document.Status, }; jobList.Add(job); } return(jobList); }
public async Task <ActionResult> Suggest(bool highlights, bool fuzzy, string term) { InitSearch(); // Setup the suggest parameters. var parameters = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 8, }; if (highlights) { parameters.HighlightPreTag = "<b>"; parameters.HighlightPostTag = "</b>"; } // Only one suggester can be specified per index. The name of the suggester is set when the suggester is specified by other API calls. // The suggester for the hotel database is called "sg" and simply searches the hotel name. DocumentSuggestResult <Hotel> suggestResult = await _indexClient.Documents.SuggestAsync <Hotel>(term, "sg", parameters); // Convert the suggest query results to a list that can be displayed in the client. List <string> suggestions = suggestResult.Results.Select(x => x.Text).ToList(); // Return the list of suggestions. return(new JsonResult(suggestions)); }
public ActionResult Suggest(bool highlights, bool fuzzy, string term) { InitSearch(); // Call suggest API and return results SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 5 }; if (highlights) { sp.HighlightPreTag = "<b>"; sp.HighlightPostTag = "</b>"; } DocumentSuggestResult suggestResult = _indexClient.Documents.Suggest(term, "sg", sp); // Convert the suggest query results to a list that can be displayed in the client. List <string> suggestions = suggestResult.Results.Select(x => x.Text).ToList(); return(new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = suggestions }); }
async Task AzureSuggestions(string text) { Suggestions.Clear(); var parameters = new SuggestParameters() { UseFuzzyMatching = true, HighlightPreTag = "[", HighlightPostTag = "]", MinimumCoverage = 100, Top = 10 }; var suggestionResults = await indexClient.Documents.SuggestAsync <Monkey>(text, "nameSuggester", parameters); foreach (var result in suggestionResults.Results) { Suggestions.Add(new Monkey { Name = result.Text, Location = result.Document.Location, Details = result.Document.Details, ImageUrl = result.Document.ImageUrl }); } }
public IEnumerable <Suggestion> GetSuggestions(SuggesterModel model, out XA.Foundation.Search.Timer queryTimer, out string indexName) { bool fuzzy = Configuration.Settings.GetBoolSetting("AzureSearchSuggesterFuzzy", false); bool highlights = Configuration.Settings.GetBoolSetting("AzureSearchSuggesterHighlight", false); ISearchIndex searchIndex = IndexResolver.ResolveIndex(!model.ContextItemID.IsNull ? ContentRepository.GetItem(model.ContextItemID) : null); indexName = searchIndex.Name; searchIndex.Initialize(); using (IProviderSearchContext searchContext = searchIndex.CreateSearchContext(SearchSecurityOptions.Default)) { SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 5 }; if (highlights) { string tag = Configuration.Settings.GetSetting("AzureSearchSuggesterHighlightTag"); sp.HighlightPreTag = $"<{tag}>"; sp.HighlightPostTag = $"</{tag}>"; } AzureSuggestQuery term = model.Term; DocumentSuggestResult <Document> handlerQueryResults; using (queryTimer = new XA.Foundation.Search.Timer()) handlerQueryResults = searchContext.Suggest(term, Configuration.Settings.GetSetting("AzureSearchSuggesterName"), sp); return(handlerQueryResults.Results.Select(a => new Suggestion() { Term = a.Text, Payload = JsonConvert.SerializeObject(a.Document) })); } }
public async Task <ActionResult> Suggest(bool highlights, bool fuzzy, string term) { // Use static variables to set up the configuration and Azure service and index clients, for efficiency. _builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); _configuration = _builder.Build(); _serviceClient = CreateSearchServiceClient(_configuration); _indexClient = _serviceClient.Indexes.GetClient("hotels"); // Call suggest API and return results SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 8, }; if (highlights) { sp.HighlightPreTag = "<b>"; sp.HighlightPostTag = "</b>"; } // Only one suggester can be specified per index. The name of the suggester is set when the suggester is specified by other API calls. // The suggester for the hotel database is called "sg" and simply searches the hotel name. DocumentSuggestResult <Hotel> suggestResult = await _indexClient.Documents.SuggestAsync <Hotel>(term, "sg", sp); // Convert the suggest query results to a list that can be displayed in the client. List <string> suggestions = suggestResult.Results.Select(x => x.Text).ToList(); return(new JsonResult((object)suggestions)); }
private Task <AzureOperationResponse <DocumentSuggestResult <T> > > DoSuggestAsync <T>( string searchText, string suggesterName, SuggestParameters suggestParameters, SearchRequestOptions searchRequestOptions, Dictionary <string, List <string> > customHeaders, JsonSerializerSettings deserializerSettings, CancellationToken cancellationToken) { if (Client.UseHttpGetForQueries) { return(Client.DocumentsProxy.SuggestGetWithHttpMessagesAsync <T>( searchText, suggesterName, suggestParameters.EnsureSelect(), searchRequestOptions, EnsureCustomHeaders(customHeaders), cancellationToken, responseDeserializerSettings: deserializerSettings)); } else { return(Client.DocumentsProxy.SuggestPostWithHttpMessagesAsync <T>( suggestParameters.ToRequest(searchText, suggesterName), searchRequestOptions, EnsureCustomHeaders(customHeaders), cancellationToken, responseDeserializerSettings: deserializerSettings)); } }
/// <summary> /// Suggests query terms based on input text and matching documents in the Azure Search index. (see /// <see href="https://msdn.microsoft.com/library/azure/dn798936.aspx"/> for more information) /// </summary> /// <typeparam name="T"> /// The CLR type that maps to the index schema. Instances of this type can be retrieved as documents /// from the index. /// </typeparam> /// <param name='operations'> /// Reference to the Microsoft.Azure.Search.IDocumentOperations. /// </param> /// <param name="searchText"> /// The search text on which to base suggestions. /// </param> /// <param name="suggesterName"> /// The name of the suggester as specified in the suggesters collection that's part of the index definition. /// </param> /// <param name="suggestParameters"> /// Parameters to further refine the suggestion query. /// </param> /// <returns> /// Response containing the suggested text and documents matching the query. /// </returns> /// <remarks> /// The generic overloads of the Suggest and SuggestAsync methods support mapping of Azure Search field types /// to .NET types via the type parameter T. See /// <see cref="IDocumentOperations.GetAsync<T>(string, System.Collections.Generic.IEnumerable<string>, CancellationToken)"/> /// for more details on the type mapping. /// </remarks> public static Task <DocumentSuggestResponse <T> > SuggestAsync <T>( this IDocumentOperations operations, string searchText, string suggesterName, SuggestParameters suggestParameters) where T : class { return(operations.SuggestAsync <T>(searchText, suggesterName, suggestParameters, CancellationToken.None)); }
public async Task <UniversitySearchDto> SearchAsync(string term, int page, string?country, CancellationToken token) { string CountryFilter(string country1) { return($"{nameof(Entities.University.Country)} eq '{country1.ToUpperInvariant()}'"); } var searchParameter = new SearchParameters { Select = _listOfSelectParams, Top = PageSize, Skip = PageSize * page, OrderBy = new List <string> { "search.score() desc", $"{Entities.University.UserCountFieldName} desc" } }; if (country != null) { searchParameter.Filter = CountryFilter(country); } term = term?.Replace("\"", "\\"); var searchDocumentResult = await _client.Documents.SearchAsync <Entities.University>(term, searchParameter, cancellationToken : token); if (searchDocumentResult.Results.Count != 0) { return(new UniversitySearchDto(searchDocumentResult.Results.Select(s => ToDto(s.Document)))); } if (page == 0 && !string.IsNullOrEmpty(term)) { var suggestParams = new SuggestParameters() { Select = _listOfSelectParams, UseFuzzyMatching = true, Top = PageSize, }; if (country != null) { suggestParams.Filter = CountryFilter(country); } var suggesterResult = await _client.Documents.SuggestAsync <Entities.University>(term, UniversitySearchWrite.SuggesterName, suggestParams , cancellationToken : token); return(new UniversitySearchDto(suggesterResult.Results.Select(s => ToDto(s.Document)))); } return(new UniversitySearchDto(Enumerable.Empty <UniversityDto>())); }
public void SelectStarPropagatesToQueryString() { var parameters = new SuggestParameters() { Select = new[] { "*" } }; Assert.Equal("$select=*&fuzzy=false", parameters.ToString()); }
public static async Task <IReadOnlyList <SuggestResult> > SuggestAsync(string searchText, Geometry.Geometry?searchArea = null, int maxResults = 10) { await _geocoder.LoadAsync().ConfigureAwait(false); SuggestParameters suggestParams = new SuggestParameters { MaxResults = maxResults, SearchArea = searchArea }; return(await _geocoder.SuggestAsync(searchText, suggestParams).ConfigureAwait(false)); }
/// <summary> /// Returns type-ahead search suggestions for the biography search box. /// </summary> /// <param name="query">The search fragment entered so far.</param> /// <param name="fuzzy">If true, use fuzzy term matching.</param> /// <returns></returns> internal async Task <DocumentSuggestResult> BiographySuggest(string query, bool fuzzy) { SuggestParameters sp = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 8 }; return(await biographyIndex.Documents.SuggestAsync(query, "biography_suggester", sp)); }
public static async Task <DocumentSuggestResult <Person> > SuggestAsync(string searchText, bool fuzzy) { SuggestParameters parameters = new SuggestParameters() { UseFuzzyMatching = fuzzy, Top = 5 }; return(await searchIndexClient.Documents.SuggestAsync <Person>(searchText, "sg", parameters)); }
public async Task <JsonResult> Suggest(string text) { var parameters = new SuggestParameters { }; var response = await Search.Documents.SuggestAsync(text, "products", parameters); var items = response.Results.Select(xx => xx.Text).ToList(); return(Json(items, JsonRequestBehavior.AllowGet)); }
public async Task <JsonResult> Suggest(string text, int pageNumber = 1, int pageSize = 20, string orderBy = "Name") { var parameters = new SuggestParameters { }; var result = await Search.Documents.SuggestAsync(text, "text", parameters); var items = result.Select(xx => xx.Text).ToList(); return(Json(items, JsonRequestBehavior.AllowGet)); }