private static SearchIndex CreateDemoIndex(SearchIndexClient indexClient) { FieldBuilder builder = new FieldBuilder(); var index = new SearchIndex("demoindex") { Fields = builder.Build(typeof(DemoIndex)) }; try { indexClient.GetIndex(index.Name); indexClient.DeleteIndex(index.Name); } catch (RequestFailedException ex) when(ex.Status == 404) { //if the specified index not exist, 404 will be thrown. } try { indexClient.CreateIndex(index); } catch (RequestFailedException ex) { Console.WriteLine("Failed to create the index\n Exception message: {0}\n", ex.Message); ExitProgram("Cannot continue without an index"); } return(index); }
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()); } }
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()); } }
// 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(); }
private async Task <SearchIndex> CreateDemoIndexAsync(SearchIndexClient indexClient) { FieldBuilder builder = new FieldBuilder(); var index = new SearchIndex(_indexName) { Fields = builder.Build(typeof(DemoIndex)) }; try { indexClient.GetIndex(index.Name); indexClient.DeleteIndex(index.Name); } catch (RequestFailedException ex) when(ex.Status == 404) { //if the specified index not exist, 404 will be thrown. } try { await indexClient.CreateIndexAsync(index); } catch (RequestFailedException ex) { throw new Exception("Failed to create the index", ex); } return(index); }
private static void CleanupSearchIndexClientResources(SearchIndexClient indexClient, SearchIndex index) { try { if (indexClient.GetIndex(index.Name) != null) { indexClient.DeleteIndex(index.Name); } } catch (RequestFailedException e) when(e.Status == 404) { //if exception occurred and status is "Not Found", this is working as expected Console.WriteLine("Failed to find index and this is because it doesn't exist."); } }
private static void DeleteIndexIfExists(string indexName, SearchIndexClient indexClient) { try { if (indexClient.GetIndex(indexName) != null) { indexClient.DeleteIndex(indexName); } } catch (RequestFailedException e) when(e.Status == 404) { //if exception occurred and status is "Not Found", this is work as expect Console.WriteLine("Failed to find index and this is because it's not there."); } }
private static void CleanupResources(SearchIndexClient indexClient) { try { if (indexClient.GetIndex("hotels") != null) { indexClient.DeleteIndex("hotels"); } if (indexClient.GetSynonymMapNames().Value.Contains("desc-synonymmap")) { indexClient.DeleteSynonymMap("desc-synonymmap"); } } catch (RequestFailedException e) when(e.Status == 404) { //if exception occurred and status is "Not Found", this is work as expect Console.WriteLine("Failed to find index and this is because it's not there."); } }
/// <summary> /// Constructor mainSearch /// </summary> /// <param name="uriService">endpoint de azure search</param> /// <param name="SearchServiceKey">key</param> /// <param name="entityIndex">índice del azure search</param> public MainSearch(string uriService, string SearchServiceKey, string entityIndex) { _searchIndex = new SearchIndexClient(new Uri(uriService), new AzureKeyCredential(SearchServiceKey), new SearchClientOptions { }); this.Index = entityIndex; this.UriService = uriService; this.ServiceKey = SearchServiceKey; try { _searchIndex.GetIndex(entityIndex); } catch (RequestFailedException exc) { if (true) { if (exc.Status == 404) { CreateOrUpdateIndex(); } else { throw exc; } } ; } catch (Exception e) { throw e; } // cliente azure _search = new SearchClient(new Uri(uriService), entityIndex, new AzureKeyCredential(SearchServiceKey)); }
private static void EnableSynonymsInHotelsIndexSafely(SearchIndexClient indexClient) { int MaxNumTries = 3; for (int i = 0; i < MaxNumTries; ++i) { try { SearchIndex index = indexClient.GetIndex("hotels"); index = AddSynonymMapsToFields(index); // The IfNotChanged condition ensures that the index is updated only if the ETags match. indexClient.CreateOrUpdateIndex(index); Console.WriteLine("Updated the index successfully.\n"); break; } catch (CloudException) { Console.WriteLine($"Index update failed : . Attempt({i}/{MaxNumTries}).\n"); } } }
static string GetIDFieldName() { // Find the id field of this index string IDFieldName = string.Empty; try { var schema = SourceIndexClient.GetIndex(SourceIndexName); foreach (var field in schema.Value.Fields) { if (field.IsKey == true) { IDFieldName = Convert.ToString(field.Name); break; } } } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message.ToString()); } return(IDFieldName); }
/// <summary> /// Get a function to access the key field of a search document. /// </summary> /// <param name="async">Whether to run sync or async.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task representing the operation.</returns> private async Task GetKeyFieldAccessorAsync(bool async, CancellationToken cancellationToken) { // Case 1: The user provided an explicit accessor and we're done if (KeyFieldAccessor != null) { return; } // Case 2: Infer the accessor from FieldBuilder try { FieldBuilder builder = new FieldBuilder { Serializer = SearchClient.Serializer }; IDictionary <string, SearchField> fields = builder.BuildMapping(typeof(T)); KeyValuePair <string, SearchField> keyField = fields.FirstOrDefault(pair => pair.Value.IsKey == true); if (!keyField.Equals(default(KeyValuePair <string, SearchField>))) { KeyFieldAccessor = CompileAccessor(keyField.Key); return; } } catch { // Ignore any errors because this type might not have been // designed with FieldBuilder in mind } // Case 3: Fetch the index to find the key Exception failure = null; try { // Call the service to find the name of the key SearchIndexClient indexClient = SearchClient.GetSearchIndexClient(); SearchIndex index = async ? await indexClient.GetIndexAsync(IndexName, cancellationToken).ConfigureAwait(false) : indexClient.GetIndex(IndexName, cancellationToken); SearchField keyField = index.Fields.Single(f => f.IsKey == true); string key = keyField.Name; if (typeof(T).IsAssignableFrom(typeof(SearchDocument))) { // Case 3a: If it's a dynamic SearchDocument, lookup // the name of the key in the dictionary KeyFieldAccessor = (T doc) => (doc as SearchDocument)?.GetString(key); return; } else { // Case 3b: We'll see if there's a property with the // same name and use that as the accessor if (typeof(T).GetProperty(key) != null || typeof(T).GetField(key) != null) { KeyFieldAccessor = CompileAccessor(key); return; } } } catch (Exception ex) { // We'll provide any exceptions as a hint because it could // be something like using the wrong API Key type when // moving from SearchClient up to SearchIndexClient that // potentially could be addressed if the user really wanted failure = ex; } // Case 4: Throw and tell the user to provide an explicit accessor. throw new InvalidOperationException( $"Failed to discover the Key field of document type {typeof(T).Name} for Azure Cognitive Search index {IndexName}. " + $"Please set {typeof(SearchIndexingBufferedSenderOptions<T>).Name}.{nameof(SearchIndexingBufferedSenderOptions<T>.KeyFieldAccessor)} explicitly.", failure);
// This sample shows how ETags work by performing conditional updates and deletes // on an Azure Search index. static async Task Main(string[] args) { IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); IConfigurationRoot configuration = builder.Build(); SearchIndexClient indexClient = CreateSearchIndexClient(configuration); Console.WriteLine("Deleting index...\n"); DeleteTestIndexIfExists(indexClient); // Every top-level resource in Azure Search has an associated ETag that keeps track of which version // of the resource you're working on. When you first create a resource such as an index, its ETag is // empty. SearchIndex index = DefineTestIndex(); Console.WriteLine( $"Test searchIndex hasn't been created yet, so its ETag should be blank. ETag: '{index.ETag}'"); // Once the resource exists in Azure Search, its ETag will be populated. Make sure to use the object // returned by the SearchIndexClient! Otherwise, you will still have the old object with the // blank ETag. //Console.WriteLine("Creating index...\n"); index = indexClient.CreateIndex(index); Console.WriteLine($"Test index created; Its ETag should be populated. ETag: '{index.ETag}'"); // ETags let you do some useful things you couldn't do otherwise. For example, by using an If-Match // condition, we can update an index using CreateOrUpdateIndexAsync() and be guaranteed that the update will only // succeed if the index already exists. index.Fields.Add(new SearchField("name", SearchFieldDataType.String) { AnalyzerName = LexicalAnalyzerName.EnMicrosoft }); index = indexClient.CreateOrUpdateIndex(index); index = await indexClient.CreateOrUpdateIndexAsync(index); Console.WriteLine( $"Test searchIndex updated; Its ETag should have changed since it was created. ETag: '{index.ETag}'"); // More importantly, ETags protect you from concurrent updates to the same resource. If another // client tries to update the resource, it will fail as long as all clients are using the right // access conditions. SearchIndex indexForClientUpdate = index; SearchIndex indexForClientUpdateFailed = indexClient.GetIndex("test"); Console.WriteLine("Simulating concurrent update. To start, both clients see the same ETag."); Console.WriteLine($"ClientUpdate ETag: '{indexForClientUpdate.ETag}' ClientUpdateFailed ETag: '{indexForClientUpdateFailed.ETag}'"); // indexForClientUpdate successfully updates the index. indexForClientUpdate.Fields.Add(new SearchField("a", SearchFieldDataType.Int32)); indexForClientUpdate = indexClient.CreateOrUpdateIndex(indexForClientUpdate); Console.WriteLine($"Test index updated by ClientUpdate; ETag: '{indexForClientUpdate.ETag}'"); // indexForClientUpdateFailed tries to update the index, but fails, thanks to the ETag check. try { indexForClientUpdateFailed.Fields.Add(new SearchField("b", SearchFieldDataType.Boolean)); indexClient.CreateOrUpdateIndex(indexForClientUpdateFailed); Console.WriteLine("Whoops; This shouldn't happen"); Environment.Exit(1); } catch (RequestFailedException e) when(e.Status == 400) { Console.WriteLine("ClientUpdateFailed failed to update the index, as expected."); } // You can also use access conditions with Delete operations. For example, you can implement an // atomic version of the DeleteTestIndexIfExists method from this sample like this: Console.WriteLine("Deleting index...\n"); indexClient.DeleteIndex("test"); // This is slightly better than using the Exists method since it makes only one round trip to // Azure Search instead of potentially two. It also avoids an extra Delete request in cases where // the resource is deleted concurrently, but this doesn't matter much since resource deletion in // Azure Search is idempotent. // And we're done! Bye! Console.WriteLine("Complete. Press any key to end application...\n"); Console.ReadKey(); }