コード例 #1
0
        // This sample shows how to create a synonym-map and an index that are encrypted with customer-managed key in Azure Key Vault
        static void Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            SearchIndexClient indexClient = CreateSearchIndexClient(configuration);

            Console.WriteLine("Cleaning up resources...\n");
            CleanupResources(indexClient);

            Console.WriteLine("Creating synonym-map encrypted with customer managed key...\n");
            CreateSynonymsEncryptedUsingCustomerManagedKey(indexClient, configuration);

            Console.WriteLine("Creating index encrypted with customer managed key...\n");
            CreateHotelsIndexEncryptedUsingCustomerManagedKey(indexClient, configuration);

            SearchIndex index = indexClient.GetIndex("hotels");

            index = AddSynonymMapsToFields(index);
            indexClient.CreateOrUpdateIndex(index);

            SearchClient searchClient = indexClient.GetSearchClient("hotels");

            Console.WriteLine("Uploading documents...\n");
            UploadDocuments(searchClient);

            SearchClient searchClientForQueries = CreateSearchClient(configuration);

            RunQueries(searchClientForQueries);

            Console.WriteLine("Complete.  Press any key to end application...\n");
            Console.ReadKey();
        }
コード例 #2
0
        public SearchResults<SearchDocument> GetFacets(string searchText, List<string> facetNames, int maxCount = 30)
        {
            var facets = new List<String>();

            foreach (var facet in facetNames) 
            {
                 facets.Add($"{facet}, count:{maxCount}");
            }

            // Execute search based on query string
            try
            {
                SearchOptions options = new SearchOptions()
                {
                    SearchMode = SearchMode.Any,
                    Size = 10,
                    QueryType = SearchQueryType.Full
                };

                foreach (string s in facetNames)
                {
                    options.Facets.Add(s);
                }
                
                return _searchIndexClient.GetSearchClient(IndexName).Search<SearchDocument>(searchText, options);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error querying index: {0}\r\n", ex.Message.ToString());
            }
            return null;
        }
コード例 #3
0
        public static async Task ValidateIndexAsync(SearchIndexClient indexClient, string indexName, long numDocsIndexed)
        {
            SearchClient searchClient = indexClient.GetSearchClient(indexName);

            long indexDocCount = await searchClient.GetDocumentCountAsync();

            while (indexDocCount != numDocsIndexed)
            {
                Console.WriteLine("Waiting for document count to update...\n");
                Thread.Sleep(2000);
                indexDocCount = await searchClient.GetDocumentCountAsync();
            }
            Console.WriteLine("Document Count is {0}\n", indexDocCount);


            var indexStats = await indexClient.GetIndexStatisticsAsync(indexName);

            while (indexStats.Value.DocumentCount != numDocsIndexed)
            {
                Console.WriteLine("Waiting for service statistics to update...\n");
                Thread.Sleep(10000);
                indexStats = await indexClient.GetIndexStatisticsAsync(indexName);
            }
            Console.WriteLine("Index Statistics: Document Count is {0}", indexStats.Value.DocumentCount);
            Console.WriteLine("Index Statistics: Storage Size is {0}\n", indexStats.Value.StorageSize);
        }
コード例 #4
0
        public static async Task Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            string searchServiceUri = configuration["SearchServiceUri"];
            string adminApiKey      = configuration["SearchServiceAdminApiKey"];
            string indexName        = configuration["SearchIndexName"];

            SearchIndexClient indexClient  = new SearchIndexClient(new Uri(searchServiceUri), new AzureKeyCredential(adminApiKey));
            SearchClient      searchClient = indexClient.GetSearchClient(indexName);

            Console.WriteLine("{0}", "Deleting index...\n");
            await DeleteIndexIfExistsAsync(indexName, indexClient);

            Console.WriteLine("{0}", "Creating index...\n");
            await CreateIndexAsync(indexName, indexClient);

            Console.WriteLine("{0}", "Finding optimal batch size...\n");
            await TestBatchSizesAsync(searchClient, numTries : 3);

            //long numDocuments = 100000;
            //DataGenerator dg = new DataGenerator();
            //List<Hotel> hotels = dg.GetHotels(numDocuments, "large");

            //Console.WriteLine("{0}", "Uploading using exponential backoff...\n");
            //await ExponentialBackoff.IndexDataAsync(searchClient, hotels, 1000, 8);

            //Console.WriteLine("{0}", "Validating all data was indexed...\n");
            //await ValidateIndexAsync(indexClient, indexName, numDocuments);

            Console.WriteLine("{0}", "Complete.  Press any key to end application...\n");
            Console.ReadKey();
        }
コード例 #5
0
        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());
            }
        }
コード例 #6
0
        static void ConfigurationSetup()
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            SourceSearchServiceName = configuration["SourceSearchServiceName"];
            SourceAdminKey          = configuration["SourceAdminKey"];
            SourceIndexName         = configuration["SourceIndexName"];
            TargetSearchServiceName = configuration["TargetSearchServiceName"];
            TargetAdminKey          = configuration["TargetAdminKey"];
            TargetIndexName         = configuration["TargetIndexName"];
            BackupDirectory         = configuration["BackupDirectory"];

            Console.WriteLine("CONFIGURATION:");
            Console.WriteLine("\n  Source service and index {0}, {1}", SourceSearchServiceName, SourceIndexName);
            Console.WriteLine("\n  Target service and index: {0}, {1}", TargetSearchServiceName, TargetIndexName);
            Console.WriteLine("\n  Backup directory: " + BackupDirectory);

            SourceIndexClient  = new SearchIndexClient(new Uri("https://" + SourceSearchServiceName + ".search.windows.net"), new AzureKeyCredential(SourceAdminKey));
            SourceSearchClient = SourceIndexClient.GetSearchClient(SourceIndexName);


            TargetIndexClient  = new SearchIndexClient(new Uri($"https://" + TargetSearchServiceName + ".search.windows.net"), new AzureKeyCredential(TargetAdminKey));
            TargetSearchClient = TargetIndexClient.GetSearchClient(TargetIndexName);
        }
コード例 #7
0
        // This sample shows how to delete, create, upload documents and query an index
        static void Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            SearchIndexClient indexClient = CreateSearchIndexClient(configuration);

            string indexName = configuration["SearchIndexName"];

            Console.WriteLine("{0}", "Deleting index...\n");
            DeleteIndexIfExists(indexName, indexClient);

            Console.WriteLine("{0}", "Creating index...\n");
            CreateIndex(indexName, indexClient);

            SearchClient searchClient = indexClient.GetSearchClient(indexName);

            Console.WriteLine("{0}", "Uploading documents...\n");
            UploadDocuments(searchClient);

            SearchClient indexClientForQueries = CreateSearchClientForQueries(indexName, configuration);

            RunQueries(indexClientForQueries);

            Console.WriteLine("{0}", "Complete.  Press any key to end application...\n");
            Console.ReadKey();
        }
コード例 #8
0
        public DocumentSearchClient(IConfiguration configuration)
        {
            try
            {
                _configuration    = configuration;
                searchServiceName = configuration.GetSection("SearchServiceName")?.Value;
                apiKey            = configuration.GetSection("SearchApiKey")?.Value;
                IndexName         = configuration.GetSection("SearchIndexName")?.Value;
                IndexerName       = configuration.GetSection("SearchIndexerName")?.Value;
                idField           = configuration.GetSection("KeyField")?.Value;
                telemetryClient.InstrumentationKey = configuration.GetSection("InstrumentationKey")?.Value;

                // Create an HTTP reference to the catalog index
                _searchIndexClient = new SearchIndexClient(new Uri($"https://{searchServiceName}.search.windows.net/"), new AzureKeyCredential(apiKey));
                _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 exceptio here, most likely you have not set your
                // credentials correctly in appsettings.json
                throw new ArgumentException(e.Message.ToString());
            }
        }
コード例 #9
0
        // This sample shows how to delete, create, upload documents and query an index with a synonym map
        static void Main(string[] args)
        {
            SearchIndexClient indexClient = CreateSearchIndexClient();

            Console.WriteLine("Cleaning up resources...\n");
            CleanupResources(indexClient);

            Console.WriteLine("Creating index...\n");
            CreateHotelsIndex(indexClient);

            SearchClient searchClient = indexClient.GetSearchClient("hotels");

            Console.WriteLine("Uploading documents...\n");
            UploadDocuments(searchClient);

            SearchClient searchClientForQueries = CreateSearchClientForQueries();

            RunQueriesWithNonExistentTermsInIndex(searchClientForQueries);

            Console.WriteLine("Adding synonyms...\n");
            UploadSynonyms(indexClient);

            Console.WriteLine("Enabling synonyms in the test index...\n");
            EnableSynonymsInHotelsIndexSafely(indexClient);
            Thread.Sleep(10000); // Wait for the changes to propagate

            RunQueriesWithNonExistentTermsInIndex(searchClientForQueries);

            Console.WriteLine("Complete.  Press any key to end application...\n");

            Console.ReadKey();
        }
コード例 #10
0
        private static SearchClient CreateSearchIndexClient()
        {
            string searchServiceEndPoint = $"http://azsearch:8080";

            var indexClient = new SearchIndexClient(new Uri(searchServiceEndPoint), new AzureKeyCredential("key"));

            return(indexClient.GetSearchClient("catalog"));
        }
コード例 #11
0
        public void GetSearchClient()
        {
            var serviceName = "my-svc-name";
            var endpoint    = new Uri($"https://{serviceName}.search.windows.net");
            var service     = new SearchIndexClient(endpoint, new AzureKeyCredential("fake"));

            var indexName = "my-index-name";
            var client    = service.GetSearchClient(indexName);

            Assert.NotNull(client);
            Assert.AreEqual(endpoint, client.Endpoint);
            Assert.AreEqual(serviceName, client.ServiceName);
            Assert.AreEqual(indexName, client.IndexName);

            Assert.Throws <ArgumentNullException>(() => service.GetSearchClient(null));
            Assert.Throws <ArgumentException>(() => service.GetSearchClient(string.Empty));
        }
コード例 #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SearchServiceTest{TOptions}"/> class.
        /// </summary>
        /// <param name="options"></param>
        public SearchServiceTest(TOptions options) : base(options)
        {
            _searchIndexClient = new SearchIndexClient(
                new Uri(PerfTestEnvironment.Instance.SearchEndPoint),
                new AzureKeyCredential(PerfTestEnvironment.Instance.SearchAccountKey));

            _indexName   = Guid.NewGuid().ToString();
            SearchClient = _searchIndexClient.GetSearchClient(_indexName);
        }
コード例 #13
0
        public AzureTextIndex(
            string serviceEndpoint,
            string serviceApiKey,
            string indexName)
        {
            indexClient = new SearchIndexClient(new Uri(serviceEndpoint), new AzureKeyCredential(serviceApiKey));

            searchClient = indexClient.GetSearchClient(indexName);
        }
コード例 #14
0
ファイル: SearchWriteClient.cs プロジェクト: arborQ/Alpaki
        private async Task <SearchClient> CreateOrUpdateIndexAsync <T>(string indexName = null)
        {
            indexName = string.IsNullOrEmpty(indexName) ? typeof(T).Name : indexName;

            var fieldBuilder = new FieldBuilder();
            var searchFields = fieldBuilder.Build(typeof(T));
            var definition   = new SearchIndex(indexName, searchFields);
            await _searchIndexClient.CreateOrUpdateIndexAsync(definition);

            return(_searchIndexClient.GetSearchClient(indexName));
        }
コード例 #15
0
        private void InitSearch()
        {
            // Create a configuration using the appsettings file.
            _builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            _configuration = _builder.Build();

            // Pull the values from the appsettings.json file.
            string searchServiceUri = _configuration["SearchServiceUri"];
            string queryApiKey      = _configuration["SearchServiceQueryApiKey"];

            // Create a service and index client.
            _indexClient  = new SearchIndexClient(new Uri(searchServiceUri), new AzureKeyCredential(queryApiKey));
            _searchClient = _indexClient.GetSearchClient("hotels-sample-index");
        }
コード例 #16
0
        // This sample shows how to use Azure Active Directory (AAD) together with Azure Search to restrict document access based on user group membership through Azure Search filters.
        public static void Main(string[] args)
        {
            // Application Id as obtained by creating an application from https://apps.dev.microsoft.com
            // See also the guided setup:https://docs.microsoft.com/en-us/azure/active-directory/develop/guidedsetups/active-directory-windesktop
            ClientId = ConfigurationManager.AppSettings["ClientId"];
            _microsoftGraphHelper = new MicrosoftGraphHelper(ClientId);
            _microsoftGraphHelper.CreateGraphServiceClient();
            string tenant = ConfigurationManager.AppSettings["Tenant"];

            // Azure Search Initialization
            string searchServicEndpoint = ConfigurationManager.AppSettings["SearchServicEndpoint"];
            string apiKey    = ConfigurationManager.AppSettings["SearchServiceApiKey"];
            string indexName = "securedfiles";

            Dictionary <Group, List <User> > groups = CreateGroupsWithUsers(tenant);

            // Create a group, a user and associate both
            _microsoftGraphHelper.CreateUsersAndGroups(groups).Wait();

            // Create a cache that contains the users and the list of groups they are part of
            Console.WriteLine("Refresh cache...\n");
            var users = groups.SelectMany(u => u.Value);

            RefreshCache(users);

            // Create an HTTP reference to the catalog index
            indexClient  = new SearchIndexClient(new Uri(searchServicEndpoint), new AzureKeyCredential(apiKey));
            searchClient = indexClient.GetSearchClient(indexName);

            if (DeleteIndex(indexName))
            {
                Console.WriteLine("Creating index...\n");
                CreateIndex(indexName);
            }

            Console.WriteLine("Indexing documents...\n");
            // Index documents with relevant group ids
            IndexDocuments(indexName, groups.Keys.Select(g => g.Id).ToList());

            foreach (var user in users)
            {
                // Retrieve user's groups so that a search filter could be built using the groups list
                Console.WriteLine("Get groups for user {0}...\n", user.UserPrincipalName);
                RefreshCacheIfRequired(user.UserPrincipalName);
                SearchQueryWithFilter(user.UserPrincipalName);
            }
        }
コード例 #17
0
        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);
            SearchIndexClient serviceClient = resources.GetIndexClient(options);

            SearchClient client = serviceClient.GetSearchClient(resources.IndexName);

            _ = await client.GetDocumentCountAsync();

            Assert.AreEqual(1, custom.RequestCount);
        }
コード例 #18
0
        private static void Main(string[] args)
        {
            string indexName = "hotels-quickstart";
            string apiKey    = "";

            // Create a SearchIndexClient to send create/delete index commands
            Uri serviceEndpoint            = new Uri($"");
            AzureKeyCredential credential  = new AzureKeyCredential(apiKey);
            SearchIndexClient  adminClient = new SearchIndexClient(serviceEndpoint, credential);

            //Console.WriteLine("{0}", "Deleting index...\n");
            //DeleteIndexIfExists(indexName, adminClient);

            // Create index
            //Console.WriteLine("{0}", "Creating index...\n");
            CreateIndex(indexName, adminClient);

            // Create a SearchClient to load and query documents
            SearchClient srchclient = new SearchClient(serviceEndpoint, indexName, credential);

            SearchClient ingesterClient = adminClient.GetSearchClient(indexName);

            // Load documents
            //Console.WriteLine("{0}", "Uploading documents...\n");
            //UploadDocuments(ingesterClient);

            // Merge or Upload documents
            //Console.WriteLine("{0}", "Merge or Upload documents...\n");
            //MergeOrUploadDocuments(ingesterClient);

            //// 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();
        }
コード例 #19
0
        private static async Task <bool> QueryIndex()
        {
            Console.WriteLine("Querying Index...");
            try
            {
                SearchClient           indexClient  = _searchIndexClient.GetSearchClient(IndexName);
                SearchResults <object> searchResult = await indexClient.SearchAsync <object>("*");

                Console.WriteLine("Number of Query Results: {0}", searchResult.GetResults().Count());
            }
            catch (Exception ex)
            {
                if (DebugMode)
                {
                    Console.WriteLine("Error querying index: {0}", ex.Message);
                }
                return(false);
            }
            return(true);
        }
コード例 #20
0
        public async Task RunAsync()
        {
            try
            {
                AnsiConsole.MarkupLine("[green]Seeding azure search...[/]");
                var fields = new FieldBuilder().Build(typeof(ProductDocument));
                var index  = new SearchIndex(nameof(ProductDocument).ToLower(), fields);
                await _searchIndexClient.CreateOrUpdateIndexAsync(index);

                var searchClient = _searchIndexClient.GetSearchClient(nameof(ProductDocument).ToLower());
                await Task.WhenAll(_seedData.Select(async product => await IndexProduct(searchClient, product)));
            }
            catch (Exception exception)
            {
                AnsiConsole.WriteException(exception, ExceptionFormats.ShortenEverything);
            }
            finally
            {
                AnsiConsole.MarkupLine("[green]Seeded azure search.[/]");
            }
        }
コード例 #21
0
        static void Main(string[] args)
        {
            string serviceName = "<Put your search service NAME here>";
            string apiKey      = "<Put your search service ADMIN API KEY here";
            string indexName   = "hotels-quickstart";

            // Create a SearchIndexClient to send create/delete index commands
            Uri serviceEndpoint            = new Uri($"https://{serviceName}.search.windows.net/");
            AzureKeyCredential credential  = new AzureKeyCredential(apiKey);
            SearchIndexClient  adminClient = 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, adminClient);

            // Create index
            Console.WriteLine("{0}", "Creating index...\n");
            CreateIndex(indexName, adminClient);

            SearchClient ingesterClient = adminClient.GetSearchClient(indexName);

            // Load documents
            Console.WriteLine("{0}", "Uploading documents...\n");
            UploadDocuments(ingesterClient);

            // 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();
        }
コード例 #22
0
        private async Task <SearchClient> CreateIndexAsync(SearchResources resources)
        {
            Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString());
            Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey);

            #region Snippet:Azure_Search_Documents_Tests_Samples_Sample05_IndexingDocuments_CreateIndex_Connect
            Uri    endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
            string key      = Environment.GetEnvironmentVariable("SEARCH_API_KEY");

            // Create a client for manipulating search indexes
            AzureKeyCredential credential  = new AzureKeyCredential(key);
            SearchIndexClient  indexClient = new SearchIndexClient(endpoint, credential);
            #endregion

            indexClient = InstrumentClient(new SearchIndexClient(endpoint, credential, GetSearchClientOptions()));

            #region Snippet:Azure_Search_Documents_Tests_Samples_Sample05_IndexingDocuments_CreateIndex_Create
            // Create the search index
            string indexName = "Products";
#if !SNIPPET
            indexName = Recording.Random.GetName();
#endif
            await indexClient.CreateIndexAsync(
                new SearchIndex(indexName)
            {
                Fields = new FieldBuilder().Build(typeof(Product))
            });

            #endregion

            #region Snippet:Azure_Search_Documents_Tests_Samples_Sample05_IndexingDocuments_CreateIndex_Client
            SearchClient searchClient = indexClient.GetSearchClient(indexName);
            #endregion

            searchClient = InstrumentClient(searchClient);

            return(searchClient);
        }
コード例 #23
0
        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
        }
コード例 #24
0
        public async Task CreateIndexerAsync()
        {
            await using SearchResources resources = await SearchResources.CreateWithBlobStorageAsync(this, populate : true);

            Environment.SetEnvironmentVariable("SEARCH_ENDPOINT", resources.Endpoint.ToString());
            Environment.SetEnvironmentVariable("SEARCH_API_KEY", resources.PrimaryApiKey);
            Environment.SetEnvironmentVariable("STORAGE_CONNECTION_STRING", resources.StorageAccountConnectionString);
            Environment.SetEnvironmentVariable("STORAGE_CONTAINER", resources.BlobContainerName);
            Environment.SetEnvironmentVariable("COGNITIVE_SERVICES_KEY", resources.CognitiveServicesKey);

            // Define clean up tasks to be invoked in reverse order added.
            Stack <Func <Task> > cleanUpTasks = new Stack <Func <Task> >();

            try
            {
                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateSynonymMap
                // Create a new SearchIndexClient
                Uri endpoint = new Uri(Environment.GetEnvironmentVariable("SEARCH_ENDPOINT"));
                AzureKeyCredential credential = new AzureKeyCredential(
                    Environment.GetEnvironmentVariable("SEARCH_API_KEY"));
                SearchIndexClient indexClient = new SearchIndexClient(endpoint, credential);
#if !SNIPPET
                indexClient = resources.GetIndexClient(new SearchClientOptions());
#endif

                // Create a synonym map from a file containing country names and abbreviations
                // using the Solr format with entry on a new line using \n, for example:
                // United States of America,US,USA\n
                string synonymMapName = "countries";
#if !SNIPPET
                synonymMapName = Recording.Random.GetName();
#endif
                string synonymMapPath = "countries.txt";
#if !SNIPPET
                synonymMapPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "Samples", "countries.txt");
#endif

                SynonymMap synonyms;
#if SNIPPET
                using (StreamReader file = File.OpenText(synonymMapPath))
                {
                    synonyms = new SynonymMap(synonymMapName, file);
                }
#else
                synonyms = new SynonymMap(synonymMapName, CountriesSolrSynonymMap);
#endif

                await indexClient.CreateSynonymMapAsync(synonyms);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateSynonymMap

                // Make sure our synonym map gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexClient.DeleteSynonymMapAsync(synonymMapName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndex
                // Create the index
                string indexName = "hotels";
#if !SNIPPET
                indexName = Recording.Random.GetName();
#endif
                SearchIndex index = new SearchIndex(indexName)
                {
                    Fields =
                    {
                        new SimpleField("hotelId",                    SearchFieldDataType.String)
                        {
                            IsKey = true,                             IsFilterable = true, IsSortable  = true
                        },
                        new SearchableField("hotelName")
                        {
                            IsFilterable = true,                      IsSortable   = true
                        },
                        new SearchableField("description")
                        {
                            AnalyzerName = LexicalAnalyzerName.EnLucene
                        },
                        new SearchableField("descriptionFr")
                        {
                            AnalyzerName = LexicalAnalyzerName.FrLucene
                        },
                        new SearchableField("tags",                   collection: true)
                        {
                            IsFilterable = true,                      IsFacetable  = true
                        },
                        new ComplexField("address")
                        {
                            Fields =
                            {
                                new SearchableField("streetAddress"),
                                new SearchableField("city")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                },
                                new SearchableField("stateProvince")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                },
                                new SearchableField("country")
                                {
                                    SynonymMapNames = new[] { synonymMapName },IsFilterable               = true, IsSortable  = true,IsFacetable          = true
                                },
                                new SearchableField("postalCode")
                                {
                                    IsFilterable = true,             IsSortable                 = true, IsFacetable = true
                                }
                            }
                        }
                    }
                };

                await indexClient.CreateIndexAsync(index);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndex

                // Make sure our synonym map gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexClient.DeleteIndexAsync(indexName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateDataSourceConnection
                // Create a new SearchIndexerClient
                SearchIndexerClient indexerClient = new SearchIndexerClient(endpoint, credential);
#if !SNIPPET
                indexerClient = resources.GetIndexerClient();
#endif

                string dataSourceConnectionName = "hotels";
#if !SNIPPET
                dataSourceConnectionName = Recording.Random.GetName();
#endif
                SearchIndexerDataSourceConnection dataSourceConnection = new SearchIndexerDataSourceConnection(
                    dataSourceConnectionName,
                    SearchIndexerDataSourceType.AzureBlob,
                    Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"),
                    new SearchIndexerDataContainer(Environment.GetEnvironmentVariable("STORAGE_CONTAINER")));

                await indexerClient.CreateDataSourceConnectionAsync(dataSourceConnection);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateDataSourceConnection

                // Make sure our data source gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteDataSourceConnectionAsync(dataSourceConnectionName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Skillset
                // Translate English descriptions to French.
                // See https://docs.microsoft.com/azure/search/cognitive-search-skill-text-translation for details of the Text Translation skill.
                TextTranslationSkill translationSkill = new TextTranslationSkill(
                    inputs: new[]
                {
                    new InputFieldMappingEntry("text")
                    {
                        Source = "/document/description"
                    }
                },
                    outputs: new[]
                {
                    new OutputFieldMappingEntry("translatedText")
                    {
                        TargetName = "descriptionFrTranslated"
                    }
                },
                    TextTranslationSkillLanguage.Fr)
                {
                    Name    = "descriptionFrTranslation",
                    Context = "/document",
                    DefaultFromLanguageCode = TextTranslationSkillLanguage.En
                };

                // Use the human-translated French description if available; otherwise, use the translated description.
                // See https://docs.microsoft.com/azure/search/cognitive-search-skill-conditional for details of the Conditional skill.
                ConditionalSkill conditionalSkill = new ConditionalSkill(
                    inputs: new[]
                {
                    new InputFieldMappingEntry("condition")
                    {
                        Source = "= $(/document/descriptionFr) == null"
                    },
                    new InputFieldMappingEntry("whenTrue")
                    {
                        Source = "/document/descriptionFrTranslated"
                    },
                    new InputFieldMappingEntry("whenFalse")
                    {
                        Source = "/document/descriptionFr"
                    }
                },
                    outputs: new[]
                {
                    new OutputFieldMappingEntry("output")
                    {
                        TargetName = "descriptionFrFinal"
                    }
                })
                {
                    Name    = "descriptionFrConditional",
                    Context = "/document",
                };

                // Create a SearchIndexerSkillset that processes those skills in the order given below.
                string skillsetName = "translations";
#if !SNIPPET
                skillsetName = Recording.Random.GetName();
#endif
                SearchIndexerSkillset skillset = new SearchIndexerSkillset(
                    skillsetName,
                    new SearchIndexerSkill[] { translationSkill, conditionalSkill })
                {
                    CognitiveServicesAccount = new CognitiveServicesAccountKey(
                        Environment.GetEnvironmentVariable("COGNITIVE_SERVICES_KEY")),
                    KnowledgeStore = new SearchIndexerKnowledgeStore(
                        Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING"),
                        new List <SearchIndexerKnowledgeStoreProjection>()),
                };

                await indexerClient.CreateSkillsetAsync(skillset);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Skillset

                // Make sure our skillset gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteSkillsetAsync(skillsetName));

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndexer
                string indexerName = "hotels";
#if !SNIPPET
                indexerName = Recording.Random.GetName();
#endif
                SearchIndexer indexer = new SearchIndexer(
                    indexerName,
                    dataSourceConnectionName,
                    indexName)
                {
                    // We only want to index fields defined in our index, excluding descriptionFr if defined.
                    FieldMappings =
                    {
                        new FieldMapping("hotelId"),
                        new FieldMapping("hotelName"),
                        new FieldMapping("description"),
                        new FieldMapping("tags"),
                        new FieldMapping("address")
                    },
                    OutputFieldMappings =
                    {
                        new FieldMapping("/document/descriptionFrFinal")
                        {
                            TargetFieldName = "descriptionFr"
                        }
                    },
                    Parameters = new IndexingParameters
                    {
                        // Tell the indexer to parse each blob as a separate JSON document.
                        IndexingParametersConfiguration = new IndexingParametersConfiguration
                        {
                            ParsingMode = BlobIndexerParsingMode.Json
                        }
                    },
                    SkillsetName = skillsetName
                };

                // Create the indexer which, upon successful creation, also runs the indexer.
                await indexerClient.CreateIndexerAsync(indexer);

                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_CreateIndexer

                // Make sure our indexer gets deleted, which is not deleted when our
                // index is deleted when our SearchResources goes out of scope.
                cleanUpTasks.Push(() => indexerClient.DeleteIndexerAsync(indexerName));

                // Wait till the indexer is done.
                await WaitForIndexingAsync(indexerClient, indexerName);

                #region Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Query
                // Get a SearchClient from the SearchIndexClient to share its pipeline.
                SearchClient searchClient = indexClient.GetSearchClient(indexName);
#if !SNIPPET
                searchClient = InstrumentClient(new SearchClient(endpoint, indexName, credential, GetSearchClientOptions()));
#endif

                // Query for hotels with an ocean view.
                SearchResults <Hotel> results = await searchClient.SearchAsync <Hotel>("ocean view");

#if !SNIPPET
                bool found = false;
#endif
                await foreach (SearchResult <Hotel> result in results.GetResultsAsync())
                {
                    Hotel hotel = result.Document;
#if !SNIPPET
                    if (hotel.HotelId == "6")
                    {
                        Assert.IsNotNull(hotel.DescriptionFr); found = true;
                    }
#endif

                    Console.WriteLine($"{hotel.HotelName} ({hotel.HotelId})");
                    Console.WriteLine($"  Description (English): {hotel.Description}");
                    Console.WriteLine($"  Description (French):  {hotel.DescriptionFr}");
                }
                #endregion Snippet:Azure_Search_Tests_Samples_CreateIndexerAsync_Query

                Assert.IsTrue(found, "Expected hotel #6 not found in search results");
            }
            finally
            {
                // We want to await these individual to create a deterministic order for playing back tests.
                foreach (Func <Task> cleanUpTask in cleanUpTasks)
                {
                    await cleanUpTask();
                }
            }
        }