private static SearchIndexerDataSourceConnection CreateOrUpdateDataSource(SearchIndexerClient indexerClient, IConfigurationRoot configuration)
        {
            SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(
                name: "demodata",
                type: SearchIndexerDataSourceType.AzureBlob,
                connectionString: configuration["AzureBlobConnectionString"],
                container: new SearchIndexerDataContainer("cog-search-demo"))
            {
                Description = "Demo files to demonstrate cognitive search capabilities."
            };

            // The data source does not need to be deleted if it was already created
            // since we are using the CreateOrUpdate method
            try
            {
                indexerClient.CreateOrUpdateDataSourceConnection(dataSource);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to create or update the data source\n Exception message: {0}\n", ex.Message);
                ExitProgram("Cannot continue without a data source");
            }

            return(dataSource);
        }
예제 #2
0
        private static SearchIndexerDataSourceConnection CreateOrUpdateDataSource(SearchIndexerClient indexerClient, IConfigurationRoot configuration)
        {
            SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(
                name: "demodata",
                type: SearchIndexerDataSourceType.AzureBlob,
                connectionString: configuration["AzureBlobConnectionString"],
                container: new SearchIndexerDataContainer(configuration["ContainerName"]))
            {
                Description = "Demo files to demonstrate cognitive search capabilities."
            };

            try
            {
                indexerClient.CreateOrUpdateDataSourceConnection(dataSource);
                Console.WriteLine("Data source successfully created");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed to create or update the data source\n Exception message: {0}\n", ex.Message);
                ExitProgram("Cannot continue without a data source");
            }

            return(dataSource);
        }
        private SearchIndexerDataSourceConnection CreateOrUpdateDataSource(SearchIndexerClient indexerClient)
        {
            SearchIndexerDataSourceConnection dataSource = new SearchIndexerDataSourceConnection(
                name: "demodata",
                type: SearchIndexerDataSourceType.AzureBlob,
                connectionString: _storageConnectionString,
                container: new SearchIndexerDataContainer(_containerName))
            {
                Description = "Demo files to demonstrate cognitive search capabilities."
            };

            // The data source does not need to be deleted if it was already created
            // since we are using the CreateOrUpdate method
            try
            {
                indexerClient.CreateOrUpdateDataSourceConnection(dataSource);
            }
            catch (Exception ex)
            {
                throw new Exception("Failed to create or update the data source", ex);
            }

            return(dataSource);
        }
        public static async Task Main(string[] args)
        {
            IConfigurationBuilder builder       = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            IConfigurationRoot    configuration = builder.Build();

            if (configuration["SearchServiceEndPoint"] == "Put your search service endpoint here")
            {
                Console.Error.WriteLine("Specify SearchServiceEndPoint in appsettings.json");
                Environment.Exit(-1);
            }

            if (configuration["SearchServiceAdminApiKey"] == "Put your search service admin API key here")
            {
                Console.Error.WriteLine("Specify SearchServiceAdminApiKey in appsettings.json");
                Environment.Exit(-1);
            }

            if (configuration["AzureSQLConnectionString"] == "Put your Azure SQL database connection string here")
            {
                Console.Error.WriteLine("Specify AzureSQLConnectionString in appsettings.json");
                Environment.Exit(-1);
            }

            SearchIndexClient   indexClient   = new SearchIndexClient(new Uri(configuration["SearchServiceEndPoint"]), new AzureKeyCredential(configuration["SearchServiceAdminApiKey"]));
            SearchIndexerClient indexerClient = new SearchIndexerClient(new Uri(configuration["SearchServiceEndPoint"]), new AzureKeyCredential(configuration["SearchServiceAdminApiKey"]));

            Console.WriteLine("Creating index...");
            FieldBuilder fieldBuilder = new FieldBuilder();
            var          searchFields = fieldBuilder.Build(typeof(Hotel));
            var          searchIndex  = new SearchIndex("hotels-sql-idx", searchFields);

            // If we have run the sample before, this index will be populated
            // We can clear the index by deleting it if it exists and creating
            // it again
            CleanupSearchIndexClientResources(indexClient, searchIndex);

            indexClient.CreateOrUpdateIndex(searchIndex);

            Console.WriteLine("Creating data source...");

            // The sample data set has a table name of "hotels"
            // The sample data set table has a "soft delete" column named IsDeleted
            // When this column is set to true and the indexer sees it, it will remove the
            // corresponding document from the search service
            // See this link for more information
            // https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.search.models.softdeletecolumndeletiondetectionpolicy
            // The sample data set uses SQL integrated change tracking for change detection
            // This means that when the indexer runs, it will be able to detect which data has
            // changed since the last run using built in change tracking
            // See this link for more information
            // https://docs.microsoft.com/en-us/sql/relational-databases/track-changes/about-change-tracking-sql-server
            var dataSource =
                new SearchIndexerDataSourceConnection(
                    "hotels-sql-ds",
                    SearchIndexerDataSourceType.AzureSql,
                    configuration["AzureSQLConnectionString"],
                    new SearchIndexerDataContainer("hotels"));

            // The data source does not need to be deleted if it was already created,
            // but the connection string may need to be updated if it was changed
            indexerClient.CreateOrUpdateDataSourceConnection(dataSource);

            Console.WriteLine("Creating Azure SQL indexer...");

            var schedule = new IndexingSchedule(TimeSpan.FromDays(1))
            {
                StartTime = DateTimeOffset.Now
            };

            var parameters = new IndexingParameters()
            {
                BatchSize              = 100,
                MaxFailedItems         = 0,
                MaxFailedItemsPerBatch = 0
            };

            // Indexer declarations require a data source and search index.
            // Common optional properties include a schedule, parameters, and field mappings
            // The field mappings below are redundant due to how the Hotel class is defined, but
            // we included them anyway to show the syntax
            var indexer = new SearchIndexer("hotels-sql-idxr", dataSource.Name, searchIndex.Name)
            {
                Description   = "Data indexer",
                Schedule      = schedule,
                Parameters    = parameters,
                FieldMappings =
                {
                    new FieldMapping("_id")
                    {
                        TargetFieldName = "HotelId"
                    },
                    new FieldMapping("Amenities")
                    {
                        TargetFieldName = "Tags"
                    }
                }
            };

            // Indexers contain metadata about how much they have already indexed
            // If we already ran the sample, the indexer will remember that it already
            // indexed the sample data and not run again
            // To avoid this, reset the indexer if it exists
            CleanupSearchIndexerClientResources(indexerClient, indexer);

            await indexerClient.CreateOrUpdateIndexerAsync(indexer);

            // We created the indexer with a schedule, but we also
            // want to run it immediately
            Console.WriteLine("Running Azure SQL indexer...");

            try
            {
                await indexerClient.RunIndexerAsync(indexer.Name);
            }
            catch (CloudException e) when(e.Response.StatusCode == (HttpStatusCode)429)
            {
                Console.WriteLine("Failed to run indexer: {0}", e.Response.Content);
            }

            // Wait 5 seconds for indexing to complete before checking status
            Console.WriteLine("Waiting for indexing...\n");
            System.Threading.Thread.Sleep(5000);

            // After an indexer run, you can retrieve status.
            CheckIndexerStatus(indexerClient, indexer);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
            Environment.Exit(0);
        }
        public void CreateCustomerIndex()
        {
            //creating index
            SearchIndexClient   indexClient   = new SearchIndexClient(Uri, keyCredential);
            SearchIndexerClient indexerClient = new SearchIndexerClient(Uri, keyCredential);

            Console.WriteLine("Creating index...");
            FieldBuilder fieldBuilder = new FieldBuilder();
            var          searchFields = fieldBuilder.Build(typeof(ServiceOrder));
            //var searchIndex = new SearchIndex("serviceorder-sql-idx", searchFields);
            var searchIndex = new SearchIndex("serviceorder-sql-idx", searchFields);

            // If we have run the sample before, this index will be populated
            // We can clear the index by deleting it if it exists and creating
            // it again
            CleanupSearchIndexClientResources(indexClient, searchIndex);

            indexClient.CreateOrUpdateIndex(searchIndex);
            //Creating data source

            Console.WriteLine("Creating data source...");

            var dataSource =
                new SearchIndexerDataSourceConnection(
                    "serviceorder-sql-ds",
                    SearchIndexerDataSourceType.AzureSql,
                    azureSQLConnectionStr,
                    new SearchIndexerDataContainer("[ServiceOrder]"));

            indexerClient.CreateOrUpdateDataSourceConnection(dataSource);

            //Creating indexer
            Console.WriteLine("Creating Azure SQL indexer...");

            //var schedule = new IndexingSchedule(TimeSpan.FromDays(1))
            //{
            //    StartTime = DateTimeOffset.Now
            //};

            var parameters = new IndexingParameters()
            {
                BatchSize              = 100,
                MaxFailedItems         = 0,
                MaxFailedItemsPerBatch = 0
            };



            // Indexer declarations require a data source and search index.
            // Common optional properties include a schedule, parameters, and field mappings
            // The field mappings below are redundant due to how the Hotel class is defined, but
            // we included them anyway to show the syntax
            var indexer = new SearchIndexer("serviceorder-sql-idxr", dataSource.Name, searchIndex.Name)
            {
                Description = "Service Order indexer",
                Schedule    = new IndexingSchedule(TimeSpan.FromMinutes(5)),
                Parameters  = parameters,
            };

            indexerClient.CreateOrUpdateIndexerAsync(indexer);

            Console.WriteLine("Running Azure SQL indexer...");

            try
            {
                indexerClient.RunIndexerAsync(indexer.Name);
            }
            catch (CloudException e) when(e.Response.StatusCode == (HttpStatusCode)429)
            {
                Console.WriteLine("Failed to run indexer: {0}", e.Response.Content);
            }

            // Wait 5 seconds for indexing to complete before checking status
            Console.WriteLine("Waiting for indexing...\n");
            System.Threading.Thread.Sleep(5000);
        }
        private void InitializeConcertsIndex(SearchIndexClient serviceClient)
        {
            // Create the index that will contain the searchable data from the concerts.
            var concertsIndex = new SearchIndex(IndexNameConcerts)
            {
                Fields = new[]
                {
                    new SearchField(nameof(Concert.Id), SearchFieldDataType.String)
                    {
                        IsKey        = true,
                        IsSearchable = false
                    },
                    new SearchField(nameof(Concert.Artist), SearchFieldDataType.String)
                    {
                        AnalyzerName = LexicalAnalyzerName.EnMicrosoft,
                        IsSearchable = true,
                    },
                    new SearchField(nameof(Concert.Genre), SearchFieldDataType.String)
                    {
                        AnalyzerName = LexicalAnalyzerName.EnMicrosoft,
                        IsSearchable = true,
                        IsFilterable = true,
                        IsFacetable  = true
                    },
                    new SearchField(nameof(Concert.Location), SearchFieldDataType.String)
                    {
                        AnalyzerName = LexicalAnalyzerName.EnMicrosoft,
                        IsSearchable = true,
                        IsFilterable = true,
                        IsFacetable  = true
                    },
                    new SearchField(nameof(Concert.Title), SearchFieldDataType.String)
                    {
                        AnalyzerName = LexicalAnalyzerName.EnMicrosoft,
                        IsSearchable = true,
                    },
                    new SearchField(nameof(Concert.Description), SearchFieldDataType.String)
                    {
                        AnalyzerName = LexicalAnalyzerName.EnMicrosoft,
                        IsSearchable = true,
                    },
                    new SearchField(nameof(Concert.Price), SearchFieldDataType.Double)
                    {
                        IsSearchable = false,
                        IsFilterable = true,
                        IsFacetable  = true,
                        IsSortable   = true,
                    },
                    new SearchField(nameof(Concert.StartTime), SearchFieldDataType.DateTimeOffset)
                    {
                        IsSearchable = false,
                        IsSortable   = true,
                        IsFilterable = true
                    },
                },
                DefaultScoringProfile = "default-scoring",
            };

            var suggester = new SearchSuggester("default-suggester", new[] { nameof(Concert.Artist), nameof(Concert.Location), nameof(Concert.Title) });

            concertsIndex.Suggesters.Add(suggester);
            concertsIndex.ScoringProfiles.Add(new ScoringProfile("default-scoring")
            {
                // Add a lot of weight to the artist and above average weight to the title.
                TextWeights = new TextWeights(new Dictionary <string, double> {
                    { nameof(Concert.Artist), 2.0 },
                    { nameof(Concert.Title), 1.5 }
                })
            });

            serviceClient.CreateOrUpdateIndex(concertsIndex);

            var searchIndexerClient = new SearchIndexerClient(this.searchServiceUri, this.azureKeyCredential);

            // Create the data source that connects to the SQL Database account containing the consult requests.
            var concertsDataSource = new SearchIndexerDataSourceConnection(IndexNameConcerts, SearchIndexerDataSourceType.AzureSql, this.concertsSqlDatabaseConnectionString, new SearchIndexerDataContainer("Concerts"))
            {
                DataChangeDetectionPolicy = new SqlIntegratedChangeTrackingPolicy()
            };

            searchIndexerClient.CreateOrUpdateDataSourceConnection(concertsDataSource);

            // Create the indexer that will pull the data from the database into the search index.
            var concertsIndexer = new SearchIndexer(name: IndexNameConcerts, dataSourceName: IndexNameConcerts, targetIndexName: IndexNameConcerts)
            {
                Schedule = new IndexingSchedule(TimeSpan.FromMinutes(5))
            };

            searchIndexerClient.CreateOrUpdateIndexer(concertsIndexer);
        }
예제 #7
0
        public void CreateIndex <T>()
        {
            string             azureSQLConnectionStr = ConfigurationManager.AppSettings["AzureSqlConnectionString"].ToString();
            Uri                Uri = new Uri(ConfigurationManager.AppSettings["SearchServiceEndPoint"]);
            string             searchServiceKey = ConfigurationManager.AppSettings["SearchServiceAdminApiKey"];
            AzureKeyCredential keyCredential    = new AzureKeyCredential(searchServiceKey);


            SearchIndexClient   indexClient   = new SearchIndexClient(Uri, keyCredential);
            SearchIndexerClient indexerClient = new SearchIndexerClient(Uri, keyCredential);

            Console.WriteLine("Creating index...");
            _logger.LogInformation("Creating index for Orion Customer");
            FieldBuilder fieldBuilder = new FieldBuilder();
            var          searchFields = fieldBuilder.Build(typeof(T));
            var          searchIndex  = new SearchIndex(GetIndexName(HdsConstants.Orion, typeof(T).ToString()), searchFields);

            CleanupSearchIndexClientResources(indexClient, searchIndex);

            indexClient.CreateOrUpdateIndex(searchIndex);


            Console.WriteLine("Creating data source...");
            _logger.LogInformation("Creating data source for Orion Customer");

            var dataSource =
                new SearchIndexerDataSourceConnection(
                    GetDataSourceName(HdsConstants.Orion, typeof(T).ToString()),
                    SearchIndexerDataSourceType.AzureSql,
                    azureSQLConnectionStr,
                    new SearchIndexerDataContainer($"[{GetTableName(typeof(T).ToString())}]"));

            indexerClient.CreateOrUpdateDataSourceConnection(dataSource);

            //Creating indexer
            Console.WriteLine("Creating Azure SQL indexer...");
            _logger.LogInformation("Creating Azure SQL indexer for Orion Customer");

            var schedule = new IndexingSchedule(TimeSpan.FromDays(1))
            {
                StartTime = DateTimeOffset.Now
            };

            var parameters = new IndexingParameters()
            {
                BatchSize              = 100,
                MaxFailedItems         = 0,
                MaxFailedItemsPerBatch = 0
            };

            var indexer = new SearchIndexer(GetIndexerName(HdsConstants.Orion, typeof(T).ToString()), dataSource.Name, searchIndex.Name)
            {
                Description = "Data indexer",
                Schedule    = schedule,
                Parameters  = parameters,
            };

            indexerClient.CreateOrUpdateIndexerAsync(indexer);


            Console.WriteLine("Running Azure SQL indexer...");

            try
            {
                indexerClient.RunIndexerAsync(indexer.Name);
            }
            catch (CloudException e) when(e.Response.StatusCode == (HttpStatusCode)429)
            {
                Console.WriteLine("Failed to run indexer: {0}", e.Response.Content);
                _logger.LogError("Failed to run indexer: {0}", e.Response.Content);
            }
        }