Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created May 21, 2023 12:12
Show Gist options
  • Save AndyButland/27e2a9d2598f8aad7775b46570e6acc1 to your computer and use it in GitHub Desktop.
Save AndyButland/27e2a9d2598f8aad7775b46570e6acc1 to your computer and use it in GitHub Desktop.
public async Task<bool> AddOrUpdatePackage(PackageDto packageDto)
{
if (!IsSearchServiceConfigured())
{
_logger.LogWarning($"Package with Id {packageDto.PackageId} failed to index with Azure search as the search service is not configured.");
return false;
}
SearchIndexClient indexClient = GetIndexClient();
await CreateIndexIfNotExists(indexClient);
...
}
private SearchIndexClient GetIndexClient()
{
if (string.IsNullOrEmpty(_searchSettings.AdminApiKey))
{
throw new InvalidOperationException($"Cannot create a search index client operations as the admin API key was not provided.");
}
return new SearchIndexClient(new Uri(_searchSettings.ServiceEndPoint), new AzureKeyCredential(_searchSettings.AdminApiKey));
}
private async Task CreateIndexIfNotExists(SearchIndexClient indexClient)
{
// Note that we can't update fields that already exist, so it's not feasible to use CreateOrUpdateIndexAsync() here.
// Rather, if fields are changed, we need to rebuild the index.
try
{
Response<SearchIndex> existingIndexResponse = await indexClient.GetIndexAsync(_searchSettings.IndexName);
return;
}
catch (RequestFailedException e) when (e.Status == 404)
{
await CreateIndex(indexClient);
}
}
private async Task CreateIndex(SearchIndexClient indexClient)
{
var fieldBuilder = new FieldBuilder();
IList<SearchField> searchFields = fieldBuilder.Build(typeof(PackageModel));
var definition = new SearchIndex(_searchSettings.IndexName, searchFields);
await indexClient.CreateIndexAsync(definition);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment