Ejemplo n.º 1
0
        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
            });
        }
Ejemplo n.º 2
0
        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>());
            }
        }
        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);
        }
        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);
        }
Ejemplo n.º 5
0
        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));
        }
        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
            });
        }
Ejemplo n.º 7
0
        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));
        }
Ejemplo n.º 8
0
        protected void TestCanSuggestDynamicDocuments()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters = new SuggestParameters()
            {
                OrderBy = new[] { "hotelId" }
            };
            DocumentSuggestResult response = client.Documents.Suggest("good", "sg", suggestParameters);

            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++)
            {
                Assert.Equal(expectedDocs[i], response.Results[i].Document);
                Assert.Equal(expectedDocs[i]["description"], response.Results[i].Text);
            }
        }
Ejemplo n.º 9
0
        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);
        }
Ejemplo n.º 10
0
        private void AssertKeySequenceEqual(DocumentSuggestResult <Hotel> response, params string[] expectedKeys)
        {
            Assert.NotNull(response.Results);

            IEnumerable <string> actualKeys = response.Results.Select(r => r.Document.HotelId);

            Assert.Equal(expectedKeys, actualKeys);
        }
Ejemplo n.º 11
0
        protected void TestFuzzyIsOffByDefault()
        {
            SearchIndexClient             client   = GetClientForQuery();
            DocumentSuggestResult <Hotel> response =
                client.Documents.Suggest <Hotel>("hitel", "sg");

            Assert.NotNull(response.Results);
            Assert.Equal(0, response.Results.Count);
        }
Ejemplo n.º 12
0
        protected void TestCanSuggestWithMinimumCoverage()
        {
            SearchIndexClient client = GetClientForQuery();

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

            Assert.Equal(100, response.Coverage);
        }
        public void ConvertToSuggestionResultRaisesArgumentNullExceptionForMissingResult()
        {
            // Arrange
            DocumentSuggestResult <JobProfileIndex> result = null;
            var suggestProperties      = A.Fake <SuggestProperties>();
            var azSearchQueryConverter = new AzSearchQueryConverter();

            // Act
            var exceptionResult = Assert.Throws <ArgumentNullException>(() => azSearchQueryConverter.ConvertToSuggestionResult(result, suggestProperties));

            // assert
            Assert.Equal("Value cannot be null. (Parameter 'result')", exceptionResult.Message);
        }
Ejemplo n.º 14
0
        protected void TestCanGetFuzzySuggestions()
        {
            SearchIndexClient client = GetClientForQuery();

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

            Assert.NotNull(response.Results);
            Assert.Equal(5, response.Results.Count);
        }
Ejemplo n.º 15
0
        protected void TestCanSuggestWithCustomContractResolver()
        {
            SearchIndexClient client = GetClientForQuery();

            client.DeserializationSettings.ContractResolver = new MyCustomContractResolver();

            var parameters = new SuggestParameters()
            {
                Select = new[] { "*" }
            };
            DocumentSuggestResult <LoudHotel> response = client.Documents.Suggest <LoudHotel>("Best", "sg", parameters);

            Assert.Equal(1, response.Results.Count);
            Assert.Equal(Data.TestDocuments[0], response.Results[0].Document.ToHotel());
        }
Ejemplo n.º 16
0
        protected void TestCanFilter()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters()
            {
                Filter  = "rating gt 3 and lastRenovationDate gt 2000-01-01T00:00:00Z",
                OrderBy = new[] { "hotelId" }       // Use OrderBy so changes in ranking don't break the test.
            };

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

            AssertKeySequenceEqual(response, "1", "5");
        }
Ejemplo n.º 17
0
        protected void TestSearchFieldsExcludesFieldsFromSuggest()
        {
            SearchIndexClient client = GetClientForQuery();

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

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

            Assert.NotNull(response.Results);
            Assert.Equal(0, response.Results.Count);
        }
Ejemplo n.º 18
0
        protected void TestTopTrimsResults()
        {
            SearchIndexClient client = GetClientForQuery();

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

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

            AssertKeySequenceEqual(response, "1", "10", "2");
        }
Ejemplo n.º 19
0
        public async Task <ActionResult> AutoCompleteAndSuggest(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 autocomplete API and return results
            AutocompleteParameters ap = new AutocompleteParameters()
            {
                AutocompleteMode = AutocompleteMode.OneTermWithContext,
                UseFuzzyMatching = false,
                Top = 1,
            };
            AutocompleteResult autocompleteResult = await _indexClient.Documents.AutocompleteAsync(term, "sg", ap);

            // Call suggest API and return results
            SuggestParameters sp = new SuggestParameters()
            {
                UseFuzzyMatching = false,
                Top = 8,
            };

            // 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);

            List <string> results = new List <string>();

            if (autocompleteResult.Results.Count > 0)
            {
                results.Add(autocompleteResult.Results[0].Text);
            }
            else
            {
                results.Add("");
            }
            for (int n = 0; n < suggestResult.Results.Count; n++)
            {
                results.Add(suggestResult.Results[n].Text);
            }
            return(new JsonResult((object)results));
        }
Ejemplo n.º 20
0
        private static void SuggestionSearch(SearchIndexClient indexClient, string suggesterText, string suggester, bool fuzzy)
        {
            SuggestParameters suggestParameters = new SuggestParameters()
            {
                Top = 10,
                UseFuzzyMatching = fuzzy,
                SearchFields     = new List <string> {
                    "Autores"
                }
            };

            DocumentSuggestResult response = indexClient.Documents.Suggest(suggesterText, suggester, suggestParameters, searchRequestOptions: new SearchRequestOptions(Guid.NewGuid()));

            foreach (var suggestion in response.Results)
            {
                Console.WriteLine("Suggestion: " + suggestion.Text);
            }
        }
Ejemplo n.º 21
0
        public IActionResult Suggest(string term)
        {
            InitSearch();

            // Call suggest API and return results
            SuggestParameters sp = new SuggestParameters()
            {
                UseFuzzyMatching = true,
                Top = 5
            };

            DocumentSuggestResult resp = _indexClient.Documents.Suggest(term, "sg", 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).ToList();

            return(new JsonResult(suggestions.ToArray()));
        }
Ejemplo n.º 22
0
        public async Task <ActionResult> AutocompleteAndSuggest(string term)
        {
            InitSearch();

            // Setup the type-ahead search parameters.
            var ap = new AutocompleteParameters()
            {
                AutocompleteMode = AutocompleteMode.OneTermWithContext,
                Top = 1,
            };
            AutocompleteResult autocompleteResult = await _indexClient.Documents.AutocompleteAsync(term, "sg", ap);

            // Setup the suggest search parameters.
            var sp = new SuggestParameters()
            {
                Top = 8,
            };

            // 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);

            // Create an empty list.
            var results = new List <string>();

            if (autocompleteResult.Results.Count > 0)
            {
                // Add the top result for type-ahead.
                results.Add(autocompleteResult.Results[0].Text);
            }
            else
            {
                // There were no type-ahead suggestions, so add an empty string.
                results.Add("");
            }
            for (int n = 0; n < suggestResult.Results.Count; n++)
            {
                // Now add the suggestions.
                results.Add(suggestResult.Results[n].Text);
            }

            // Return the list.
            return(new JsonResult(results));
        }
        public ActionResult Suggest(string text = "")
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new JsonResult(""));
            }
            bool fuzzy = true;

            DocumentSuggestResult <Document> suggestResult = _docSearch.Suggest(text, fuzzy);

            if (suggestResult == null)
            {
                return(new JsonResult(""));
            }
            List <string> suggestions = suggestResult.Results.Select(x => x.Text).ToList();
            JsonResult    res         = new  JsonResult(suggestions[0]);

            return(res);
        }
        public SuggestionResult <T> ConvertToSuggestionResult <T>(DocumentSuggestResult <T> result, SuggestProperties properties)
            where T : class
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            return(new SuggestionResult <T>
            {
                Coverage = result.Coverage,
                Results = result.ToSuggestResultItems(),
            });
        }
Ejemplo n.º 25
0
        protected void TestCanSuggestStaticallyTypedDocuments()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters = new SuggestParameters()
            {
                OrderBy = new[] { "hotelId" }
            };
            DocumentSuggestResult <Hotel> response =
                client.Documents.Suggest <Hotel>("more", "sg", suggestParameters);

            Assert.Null(response.Coverage);
            Assert.NotNull(response.Results);

            IEnumerable <Hotel> expectedDocs =
                Data.TestDocuments.Where(h => h.HotelId == "8" || h.HotelId == "10").OrderBy(h => h.HotelId);

            Assert.Equal(expectedDocs, response.Results.Select(r => r.Document));
            Assert.Equal(expectedDocs.Select(h => h.Description), response.Results.Select(r => r.Text));
        }
Ejemplo n.º 26
0
        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)')"
                }
            };

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

            AssertKeySequenceEqual(response, "1", "9", "4", "3", "5");
        }
Ejemplo n.º 27
0
        public async Task <ActionResult> AutocompleteAndSuggest(string term)
        {
            InitSearch();

            // Setup the type-ahead search parameters.
            var ap = new AutocompleteParameters
            {
                AutocompleteMode = AutocompleteMode.OneTermWithContext,
                Top = 1
            };
            AutocompleteResult autocompleteResult = await _indexClient.Documents.AutocompleteAsync(term, "sg", ap);

            // Setup the suggest search parameters.
            var sp = new SuggestParameters
            {
                Top = 8
            };

            DocumentSuggestResult <Hotel> suggestResult =
                await _indexClient.Documents.SuggestAsync <Hotel>(term, "sg", sp);

            var results = new List <string>();

            if (autocompleteResult.Results.Count > 0)
            {
                // Add the top result for type-ahead
                results.Add(autocompleteResult.Results[0].Text);
            }
            else
            {
                // There were no type-ahead suggestions, so add an empty string.
                results.Add(string.Empty);
            }

            foreach (var result in suggestResult.Results)
            {
                results.Add(result.Text);
            }

            return(new JsonResult(results));
        }
Ejemplo n.º 28
0
        public async Task <ActionResult> Suggest(bool highlights, bool fuzzy, string term)
        {
            InitSearch();

            var parameters = new SuggestParameters()
            {
                UseFuzzyMatching = fuzzy,
                Top = 8
            };

            if (highlights)
            {
                parameters.HighlightPreTag  = "<b>";
                parameters.HighlightPostTag = "</b>";
            }

            DocumentSuggestResult <Hotel> suggestResult = await _indexClient.Documents.SuggestAsync <Hotel>(term, "sg", parameters);

            List <string> suggestions = suggestResult.Results.Select(x => x.Text).ToList();

            return(new JsonResult(suggestions));
        }
Ejemplo n.º 29
0
        protected void TestCanSuggestWithSelectedFields()
        {
            SearchIndexClient client = GetClientForQuery();

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

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

            var expectedDoc = new Hotel()
            {
                HotelName = "Fancy Stay", BaseRate = 199.0
            };

            Assert.NotNull(response.Results);
            Assert.Equal(1, response.Results.Count);
            Assert.Equal(expectedDoc, response.Results.First().Document);
        }
Ejemplo n.º 30
0
        protected void TestCanUseHitHighlighting()
        {
            SearchIndexClient client = GetClientForQuery();

            var suggestParameters =
                new SuggestParameters()
            {
                HighlightPreTag  = "<b>",
                HighlightPostTag = "</b>",
                Filter           = "category eq 'Luxury'",
                Top = 1
            };

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

            AssertKeySequenceEqual(response, "1");

            Assert.True(
                response.Results[0].Text.StartsWith("Best <b>hotel</b> in town", StringComparison.Ordinal),
                String.Format(CultureInfo.InvariantCulture, "Actual text: {0}", response.Results[0].Text));
        }