|
| 1 | +using Azure; |
| 2 | +using Azure.Search.Documents; |
| 3 | +using Azure.Search.Documents.Indexes; |
| 4 | +using Azure.Search.Documents.Models; |
| 5 | +using Cosmos.DataTransfer.CognitiveSearchExtension.Settings; |
| 6 | +using Cosmos.DataTransfer.Interfaces; |
| 7 | +using Microsoft.Extensions.Configuration; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using System.ComponentModel.Composition; |
| 10 | +using System.Diagnostics; |
| 11 | +using System.Dynamic; |
| 12 | + |
| 13 | +namespace Cosmos.DataTransfer.CognitiveSearchExtension |
| 14 | +{ |
| 15 | + [Export(typeof(IDataSinkExtension))] |
| 16 | + public class CognitiveSearchDataSinkExtension : IDataSinkExtension |
| 17 | + { |
| 18 | + public string DisplayName => "CognitiveSearch"; |
| 19 | + |
| 20 | + public async Task WriteAsync(IAsyncEnumerable<IDataItem> dataItems, IConfiguration config, IDataSourceExtension dataSource, ILogger logger, CancellationToken cancellationToken = default) |
| 21 | + { |
| 22 | + var settings = config.Get<CognitiveSearchDataSinkSettings>(); |
| 23 | + settings.Validate(); |
| 24 | + |
| 25 | + var indexClient = new SearchIndexClient(new Uri(settings.Endpoint!), new AzureKeyCredential(settings.ApiKey!)); |
| 26 | + var searchClient = indexClient.GetSearchClient(settings.Index); |
| 27 | + |
| 28 | + var convertedObjects = dataItems.Select(di => BuildObject(di)).Where(o => o != null).OfType<ExpandoObject>(); |
| 29 | + var batches = convertedObjects.Buffer(settings.BatchSize); |
| 30 | + |
| 31 | + int totalSucceededCount = 0; |
| 32 | + int totalFailedCount = 0; |
| 33 | + var timer = Stopwatch.StartNew(); |
| 34 | + await foreach (var batch in batches.WithCancellation(cancellationToken)) |
| 35 | + { |
| 36 | + var result = await searchClient.IndexDocumentsAsync( |
| 37 | + settings.IndexAction switch |
| 38 | + { |
| 39 | + IndexActionType.Upload => IndexDocumentsBatch.Upload(batch), |
| 40 | + IndexActionType.Delete => IndexDocumentsBatch.Delete(batch), |
| 41 | + IndexActionType.Merge => IndexDocumentsBatch.Merge(batch), |
| 42 | + IndexActionType.MergeOrUpload => IndexDocumentsBatch.MergeOrUpload(batch), |
| 43 | + _ => throw new InvalidOperationException() |
| 44 | + } |
| 45 | + , cancellationToken: cancellationToken); |
| 46 | + |
| 47 | + var succeededCount = result.Value.Results.Count(r => r.Succeeded); |
| 48 | + var failedCount = result.Value.Results.Count(r => !r.Succeeded); |
| 49 | + totalSucceededCount += succeededCount; |
| 50 | + totalFailedCount += failedCount; |
| 51 | + |
| 52 | + logger.LogInformation("Succeeded {Succeeded},Faild {Failed} documents indexed after {TotalSeconds}s", succeededCount, failedCount, $"{timer!.ElapsedMilliseconds / 1000.0:F2}"); |
| 53 | + foreach (var r in result.Value.Results.Where(r => !r.Succeeded)) |
| 54 | + { |
| 55 | + logger.LogWarning("Key:{Key},Status:{Status},ErrorMessage{ErrorMessage}", r.Key, r.Status, r.ErrorMessage); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + logger.LogInformation("Succeeded {Succeeded},Faild {Failed} documents indexed in {TotalSeconds}s", totalSucceededCount, totalFailedCount, $"{timer.ElapsedMilliseconds / 1000.0:F2}"); |
| 60 | + } |
| 61 | + |
| 62 | + private static ExpandoObject? BuildObject(IDataItem? source) |
| 63 | + { |
| 64 | + if (source == null) |
| 65 | + return null; |
| 66 | + |
| 67 | + var fields = source.GetFieldNames().ToList(); |
| 68 | + var item = new ExpandoObject(); |
| 69 | + foreach (string field in fields) |
| 70 | + { |
| 71 | + object? value = source.GetValue(field); |
| 72 | + var fieldName = field; |
| 73 | + if (value is IDataItem child) |
| 74 | + { |
| 75 | + value = BuildObject(child); |
| 76 | + } |
| 77 | + else if (value is IEnumerable<object?> array) |
| 78 | + { |
| 79 | + value = array.Select(dataItem => |
| 80 | + { |
| 81 | + if (dataItem is IDataItem childObject) |
| 82 | + { |
| 83 | + return BuildObject(childObject); |
| 84 | + } |
| 85 | + return dataItem; |
| 86 | + }).ToArray(); |
| 87 | + } |
| 88 | + |
| 89 | + item.TryAdd(fieldName, value); |
| 90 | + } |
| 91 | + |
| 92 | + return item; |
| 93 | + } |
| 94 | + } |
| 95 | +} |
0 commit comments