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);
            }
        }
Exemplo n.º 2
0
        public async Task<IList<SuggestResult<ProductInfo>>> SuggestAsync(string searchText)
        {
            var parameters = new SuggestParameters
            {
                UseFuzzyMatching = true,
                HighlightPreTag = "<b>",
                HighlightPostTag = "</b>"
            };

            var result = await indexClient.Documents.SuggestAsync<ProductInfo>(searchText, "product-suggester", parameters);
            return result.StatusCode != HttpStatusCode.OK ? null : result.Results;
        }
        private string[] AzureSearch(string id)
        {
            var sp = new SuggestParameters()
              {
            UseFuzzyMatching = true,
            Top = 10
              };

              ///  COnnect this to type-ahead
              var suggestions = _IndexClient.Documents.Suggest(id, "sg", sp);
              return suggestions.Select(i => i.Document["NuGetIdRaw"].ToString()).ToArray();
        }
        public void AllOpenStringParametersAreEscaped()
        {
            const string UnescapedString = "a+%=@#b";
            const string EscapedString = "a%2B%25%3D%40%23b";

            var parameters =
                new SuggestParameters()
                {
                    Filter = UnescapedString,
                    HighlightPreTag = UnescapedString,
                    HighlightPostTag = UnescapedString
                };

            const string ExpectedQueryStringFormat =
                "$filter={0}&highlightPreTag={0}&highlightPostTag={0}&$select=*&fuzzy=false";

            Assert.Equal(String.Format(ExpectedQueryStringFormat, EscapedString), parameters.ToString());
        }
Exemplo n.º 5
0
        public DocumentSuggestResponse Suggest(string searchText, bool fuzzy)
        {
            // Execute search based on query string
            try
            {
                SuggestParameters sp = new SuggestParameters()
                {
                    UseFuzzyMatching = fuzzy,
                    Top = 8
                };

                return _indexClient.Documents.Suggest(searchText, "sg", sp);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error querying index: {0}\r\n", ex.Message.ToString());
            }
            return null;
        }
        public void AllOptionsPropagatedToQueryString()
        {
            var parameters =
                new SuggestParameters()
                {
                    Filter = "field eq value",
                    HighlightPreTag = "<b>",
                    HighlightPostTag = "</b>",
                    OrderBy = new[] { "field1 asc", "field2 desc" },
                    SearchFields = new[] { "field1", "field2" },
                    Select = new[] { "field1", "field2" },
                    Top = 5,
                    UseFuzzyMatching = true
                };

            const string ExpectedQueryString =
                "$filter=field%20eq%20value&highlightPreTag=%3Cb%3E&highlightPostTag=%3C%2Fb%3E&" +
                "$orderby=field1 asc,field2 desc&searchFields=field1,field2&$select=field1,field2&" +
                "$top=5&fuzzy=true";

            Assert.Equal(ExpectedQueryString, parameters.ToString());
        }
        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));
        }
        protected void TestCanFilter()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters() { Filter = "rating gt 3 and lastRenovationDate gt 2000-01-01T00:00:00Z" };
            DocumentSuggestResponse<Hotel> response =
                client.Documents.Suggest<Hotel>("hotel", "sg", suggestParameters);

            AssertKeySequenceEqual(response, "1", "5");
        }
        protected void TestCanSuggestWithMinimumCoverage()
        {
            SearchIndexClient client = GetClientForQuery();

            var parameters = new SuggestParameters() { MinimumCoverage = 50 };
            DocumentSuggestResponse<Hotel> response = client.Documents.Suggest<Hotel>("luxury", "sg", parameters);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(100, response.Coverage);
        }
        protected void TestCanSuggestWithDateTimeInStaticModel()
        {
            SearchServiceClient serviceClient = Data.GetSearchServiceClient();

            Index index =
                new Index()
                {
                    Name = TestUtilities.GenerateName(),
                    Fields = new[]
                    {
                        new Field("ISBN", DataType.String) { IsKey = true },
                        new Field("Title", DataType.String) { IsSearchable = true },
                        new Field("Author", DataType.String),
                        new Field("PublishDate", DataType.DateTimeOffset)
                    },
                    Suggesters = new[] { new Suggester("sg", SuggesterSearchMode.AnalyzingInfixMatching, "Title") }
                };

            IndexDefinitionResponse createIndexResponse = serviceClient.Indexes.Create(index);
            SearchIndexClient indexClient = Data.GetSearchIndexClient(createIndexResponse.Index.Name);

            var doc1 = new Book() { ISBN = "123", Title = "Lord of the Rings", Author = "J.R.R. Tolkien" };
            var doc2 = new Book() { ISBN = "456", Title = "War and Peace", PublishDate = new DateTime(2015, 8, 18) };
            var batch = IndexBatch.Create(IndexAction.Create(doc1), IndexAction.Create(doc2));

            indexClient.Documents.Index(batch);
            SearchTestUtilities.WaitForIndexing();

            var parameters = new SuggestParameters() { Select = new[] { "ISBN", "Title", "PublishDate" } };
            DocumentSuggestResponse<Book> response = indexClient.Documents.Suggest<Book>("War", "sg", parameters);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(1, response.Results.Count);
            Assert.Equal(doc2, response.Results[0].Document);
        }
        protected void TestCanSuggestWithSelectedFields()
        {
            SearchIndexClient client = GetClientForQuery();

            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);
        }
        protected void TestSearchFieldsExcludesFieldsFromSuggest()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters()
                {
                    SearchFields = new[] { "hotelName" },
                };

            DocumentSuggestResponse<Hotel> response =
                client.Documents.Suggest<Hotel>("luxury", "sg", suggestParameters);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(response.Results);
            Assert.Equal(0, response.Results.Count);
        }
Exemplo n.º 13
0
        private void SetupUI() 
        {
            Title = BeerDrinkin.Core.Helpers.Strings.Search_Title;
            searchBar.Layer.BorderWidth = 1;
            searchBar.Layer.BorderColor = "15A9FE".ToUIColor().CGColor;

            serviceClient = new SearchServiceClient("beerdrinkin", new SearchCredentials(Core.Helpers.Keys.AzureSearchKey));
            indexClient = serviceClient.Indexes.GetClient("beers");

            View.AddSubview(suggestionsTableView);

            var dataSource = new SearchPlaceholderDataSource(this);
            placeHolderTableView.Source = dataSource;
            placeHolderTableView.ReloadData();
            placeHolderTableView.BackgroundColor = "F7F7F7".ToUIColor();
            placeHolderTableView.ContentInset = new UIEdgeInsets(10, 0, 0, 0);
            placeHolderTableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
            placeHolderTableView.ScrollsToTop = true;

            searchResultsTableView.ScrollsToTop = true;

            View.BringSubviewToFront(placeHolderTableView);

            searchBar.TextChanged += async delegate
            {
                 
                var connected = await Plugin.Connectivity.CrossConnectivity.Current.IsReachable("google.com", 1000);
                if(!connected)
                    return;

                if(searchBar.Text != "")
                {
                    View.BringSubviewToFront(suggestionsTableView);

                    var suggestParameters = new SuggestParameters();
                    suggestParameters.UseFuzzyMatching = true;
                    suggestParameters.Top = 25;
                    suggestParameters.HighlightPreTag = "[";
                    suggestParameters.HighlightPostTag = "]";
                    suggestParameters.MinimumCoverage = 100;
                                               
                    var response = await indexClient.Documents.SuggestAsync<BeerDrinkin.Models.IndexedBeer>(searchBar.Text, "nameSuggester", suggestParameters);                    
                    var results = new List<string>();
                    foreach(var r in response)
                    {
                        results.Add(r.Text);
                    }

                    var suggestionSource = new SearchSuggestionDataSource(results); 
                    suggestionSource.SelectedRow += (int index) =>
                    {
                        searchBar.Text = response.Results[index].Document.Name;
                        SearchForBeers(this, null);
                    };
                    suggestionsTableView.Source = suggestionSource;
                    suggestionsTableView.ReloadData();
                }
                else
                {
                    View.BringSubviewToFront(placeHolderTableView);
                }
            };

        }
        public async Task<List<Beer>> Get(string searchTerm)
        {
            try
            {
                //Setup tracking how long the HTTP request takes.
                telemtryClient.Context.Operation.Id = Guid.NewGuid().ToString();
                telemtryClient.Context.Operation.Name = "Search";
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();

                //Log the fact we've search some beers
                telemtryClient.TrackEvent("SearchedBeers");
                indexClient = serviceClient.Indexes.GetClient("beers");

                //Setup suggestionParmeters for AzureSearch
                var suggestParameters = new SuggestParameters();
                suggestParameters.UseFuzzyMatching = true;
                suggestParameters.Top = 25;
                suggestParameters.HighlightPreTag = "[";
                suggestParameters.HighlightPostTag = "]";
                suggestParameters.MinimumCoverage = 100;

                var suggestions = await indexClient.Documents.SuggestAsync<AzureSearchBeerResponse>(searchTerm, "nameSuggester", suggestParameters);

                //Convert to Beer Drinkin Beer Type & save to our DB.
                var results = new List<Beer>();
                foreach (var result in suggestions.Results)
                {
                    var indexedBeer = result.Document;
                    var beer = new Beer
                    {
                        Id = indexedBeer.Id,
                        Abv = indexedBeer.Abv,
                        Description = indexedBeer.Description,
                        BreweryDbId = indexedBeer.Id,
                        Name = indexedBeer.Name
                    };

                    beer.Image = new Image();
                    //Fetch Brewery information 

                    if(indexedBeer.Images.Count() > 0)
                    {
                        beer.HasImages = true;
                        beer.Image.SmallUrl = indexedBeer?.Images[0];
                        beer.Image.MediumUrl = indexedBeer?.Images[1];
                        beer.Image.LargeUrl = indexedBeer?.Images[2];
                    }
                    results.Add(beer);
                }

                stopwatch.Stop();
                telemtryClient.TrackRequest("BeerSearch", DateTime.Now, stopwatch.Elapsed, "200", true);

                return results;
            }
            catch(Exception ex)
            {
                telemtryClient.TrackException(ex);
                return new List<DataObjects.Beer>();
            }
        }
        public void MissingParametersAreMissingInThePayload()
        {
            var parameters = new SuggestParameters();

            // Search text and suggester name can never be null.
            SuggestParametersPayload payload = parameters.ToPayload("find me", "mySuggester");

            Assert.Null(payload.Filter);
            Assert.Null(payload.HighlightPostTag);
            Assert.Null(payload.HighlightPreTag);
            Assert.Null(payload.MinimumCoverage);
            Assert.Null(payload.OrderBy);
            Assert.Equal("find me", payload.Search);
            Assert.Null(payload.SearchFields);
            Assert.Equal("*", payload.Select);  // Nothing selected for Suggest means select everything.
            Assert.Equal("mySuggester", payload.SuggesterName);
            Assert.Null(payload.Top);
            Assert.True(payload.Fuzzy.HasValue);
            Assert.False(payload.Fuzzy.Value);  // Fuzzy is non-nullable in the client-side contract.
        }
Exemplo n.º 16
0
 public DocumentSuggestResponse Suggest(string searchText, bool blnFuzzy)
 {
     // Execute search based on query string
     try
     {
         //Build the SearchParameter object
         SearchParameters sp = new SearchParameters();
         sp.SearchMode = SearchMode.All;
         SuggestParameters sugp = new SuggestParameters();
         sugp.UseFuzzyMatching = blnFuzzy;
         return _indexClient.Documents.Suggest(searchText, "quoteauthor", sugp);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error querying index: {0}\r\n", ex.Message.ToString());
     }
     return null;
 }
        protected void TestCanGetFuzzySuggestions()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters = new SuggestParameters() { UseFuzzyMatching = true };
            DocumentSuggestResponse<Hotel> response =
                client.Documents.Suggest<Hotel>("hitel", "sg", suggestParameters);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(response.Results);
            Assert.Equal(5, response.Results.Count);
        }
        protected void TestSuggestThrowsWhenRequestIsMalformed()
        {
            SearchIndexClient client = GetClient();

            var invalidParameters = new SuggestParameters() { OrderBy = new[] { "This is not a valid orderby." } };
            CloudException e =
                Assert.Throws<CloudException>(() => client.Documents.Suggest("hotel", "sg", invalidParameters));

            Assert.Equal(HttpStatusCode.BadRequest, e.Response.StatusCode);
            Assert.Contains(
                "Invalid expression: Syntax error at position 7 in 'This is not a valid orderby.'",
                e.Message);
        }
        protected void TestCanUseHitHighlighting()
        {
            SearchIndexClient client = GetClientForQuery();

            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));
        }
 public void SelectStarPropagatesToQueryString()
 {
     var parameters = new SuggestParameters() { Select = new[] { "*" } };
     Assert.Equal("$select=*&fuzzy=false", parameters.ToString());
 }
        protected void TestOrderByProgressivelyBreaksTies()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters()
                {
                    OrderBy = new string[] 
                    { 
                        "rating desc",
                        "lastRenovationDate asc",
                        "geo.distance(location, geography'POINT(-122.0 49.0)')"
                    }
                };

            DocumentSuggestResponse<Hotel> response =
                client.Documents.Suggest<Hotel>("hotel", "sg", suggestParameters);

            AssertKeySequenceEqual(response, "1", "4", "3", "5", "2");
        }
        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);
        }
        protected void TestTopTrimsResults()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters()
                {
                    OrderBy = new string[] { "hotelId" },
                    Top = 3
                };

            DocumentSuggestResponse<Hotel> response =
                client.Documents.Suggest<Hotel>("hotel", "sg", suggestParameters);

            AssertKeySequenceEqual(response, "1", "2", "3");
        }