forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzureAISearchCollection.cs
More file actions
816 lines (697 loc) · 34.9 KB
/
Copy pathAzureAISearchCollection.cs
File metadata and controls
816 lines (697 loc) · 34.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.VectorData;
using Microsoft.Extensions.VectorData.ProviderServices;
using MEAI = Microsoft.Extensions.AI;
namespace Microsoft.SemanticKernel.Connectors.AzureAISearch;
/// <summary>
/// Service for storing and retrieving vector records, that uses Azure AI Search as the underlying storage.
/// </summary>
/// <typeparam name="TKey">The data type of the record key. Must be <see cref="string"/>.</typeparam>
/// <typeparam name="TRecord">The data model to use for adding, updating and retrieving data from storage.</typeparam>
#pragma warning disable CA1711 // Identifiers should not have incorrect suffix
public class AzureAISearchCollection<TKey, TRecord> : VectorStoreCollection<TKey, TRecord>, IKeywordHybridSearchable<TRecord>
where TKey : notnull
where TRecord : class
#pragma warning restore CA1711 // Identifiers should not have incorrect suffix
{
/// <summary>Metadata about vector store record collection.</summary>
private readonly VectorStoreCollectionMetadata _collectionMetadata;
/// <summary>The default options for vector search.</summary>
private static readonly VectorSearchOptions<TRecord> s_defaultVectorSearchOptions = new();
/// <summary>The default options for hybrid vector search.</summary>
private static readonly HybridSearchOptions<TRecord> s_defaultKeywordVectorizedHybridSearchOptions = new();
/// <summary>Azure AI Search client that can be used to manage the list of indices in an Azure AI Search Service.</summary>
private readonly SearchIndexClient _searchIndexClient;
/// <summary>Azure AI Search client that can be used to manage data in an Azure AI Search Service index.</summary>
private readonly SearchClient _searchClient;
/// <summary>A mapper to use for converting between the data model and the Azure AI Search record.</summary>
private readonly IAzureAISearchMapper<TRecord> _mappper;
/// <summary>The model for this collection.</summary>
private readonly CollectionModel _model;
/// <summary>
/// Initializes a new instance of the <see cref="AzureAISearchCollection{TKey, TRecord}"/> class.
/// </summary>
/// <param name="searchIndexClient">Azure AI Search client that can be used to manage the list of indices in an Azure AI Search Service.</param>
/// <param name="name">The name of the collection that this <see cref="AzureAISearchCollection{TKey, TRecord}"/> will access.</param>
/// <param name="options">Optional configuration options for this class.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="searchIndexClient"/> is null.</exception>
/// <exception cref="ArgumentException">Thrown when options are misconfigured.</exception>
[RequiresUnreferencedCode("The Azure AI Search provider is currently incompatible with trimming.")]
[RequiresDynamicCode("The Azure AI Search provider is currently incompatible with NativeAOT.")]
public AzureAISearchCollection(SearchIndexClient searchIndexClient, string name, AzureAISearchCollectionOptions? options = default)
: this(
searchIndexClient,
name,
static options => typeof(TRecord) == typeof(Dictionary<string, object?>)
? throw new NotSupportedException(VectorDataStrings.NonDynamicCollectionWithDictionaryNotSupported(typeof(AzureAISearchDynamicCollection)))
: new AzureAISearchModelBuilder()
.Build(typeof(TRecord), typeof(TKey), options.Definition, options.EmbeddingGenerator, options.JsonSerializerOptions ?? JsonSerializerOptions.Default),
options)
{
}
internal AzureAISearchCollection(SearchIndexClient searchIndexClient, string name, Func<AzureAISearchCollectionOptions, CollectionModel> modelFactory, AzureAISearchCollectionOptions? options)
{
// Verify.
Verify.NotNull(searchIndexClient);
Verify.NotNullOrWhiteSpace(name);
if (typeof(TKey) != typeof(string) && typeof(TKey) != typeof(Guid) && typeof(TKey) != typeof(object))
{
throw new NotSupportedException("Only string and Guid keys are supported.");
}
options ??= AzureAISearchCollectionOptions.Default;
// Assign.
this.Name = name;
this._model = modelFactory(options);
this._searchIndexClient = searchIndexClient;
this._searchClient = this._searchIndexClient.GetSearchClient(name);
this._mappper = typeof(TRecord) == typeof(Dictionary<string, object?>) ?
(IAzureAISearchMapper<TRecord>)(object)new AzureAISearchDynamicMapper(this._model, options.JsonSerializerOptions) :
new AzureAISearchMapper<TRecord>(this._model, options.JsonSerializerOptions);
this._collectionMetadata = new()
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = searchIndexClient.ServiceName,
CollectionName = name
};
}
/// <inheritdoc />
public override string Name { get; }
/// <inheritdoc />
public override async Task<bool> CollectionExistsAsync(CancellationToken cancellationToken = default)
{
try
{
await this._searchIndexClient.GetIndexAsync(this.Name, cancellationToken).ConfigureAwait(false);
return true;
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
return false;
}
catch (RequestFailedException ex)
{
throw new VectorStoreException("Call to vector store failed.", ex)
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = this._collectionMetadata.VectorStoreName,
CollectionName = this.Name,
OperationName = "GetIndex"
};
}
}
/// <inheritdoc />
public override async Task EnsureCollectionExistsAsync(CancellationToken cancellationToken = default)
{
const string OperationName = "CreateIndex";
// Don't even try to create if the collection already exists.
if (await this.CollectionExistsAsync(cancellationToken).ConfigureAwait(false))
{
return;
}
var vectorSearchConfig = new VectorSearch();
var searchFields = new List<SearchField>();
// Loop through all properties and create the search fields.
foreach (var property in this._model.Properties)
{
switch (property)
{
case KeyPropertyModel p:
searchFields.Add(AzureAISearchCollectionCreateMapping.MapKeyField(p));
break;
case DataPropertyModel p:
searchFields.Add(AzureAISearchCollectionCreateMapping.MapDataField(p));
break;
case VectorPropertyModel p:
(VectorSearchField vectorSearchField, VectorSearchAlgorithmConfiguration algorithmConfiguration, VectorSearchProfile vectorSearchProfile) = AzureAISearchCollectionCreateMapping.MapVectorField(p);
// Add the search field, plus its profile and algorithm configuration to the search config.
searchFields.Add(vectorSearchField);
vectorSearchConfig.Algorithms.Add(algorithmConfiguration);
vectorSearchConfig.Profiles.Add(vectorSearchProfile);
break;
default:
throw new UnreachableException();
}
}
// Create the index definition.
var searchIndex = new SearchIndex(this.Name, searchFields);
searchIndex.VectorSearch = vectorSearchConfig;
try
{
await this._searchIndexClient.CreateIndexAsync(searchIndex, cancellationToken).ConfigureAwait(false);
}
catch (RequestFailedException ex) when (ex.ErrorCode == "ResourceNameAlreadyInUse")
{
// Index already exists, ignore.
}
catch (RequestFailedException ex)
{
throw new VectorStoreException("Call to vector store failed.", ex)
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = this._collectionMetadata.VectorStoreName,
CollectionName = this.Name,
OperationName = OperationName
};
}
catch (AggregateException ex) when (ex.InnerException is RequestFailedException innerEx)
{
throw new VectorStoreException("Call to vector store failed.", ex)
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = this._collectionMetadata.VectorStoreName,
CollectionName = this.Name,
OperationName = OperationName
};
}
}
/// <inheritdoc />
public override Task EnsureCollectionDeletedAsync(CancellationToken cancellationToken = default)
{
return this.RunOperationAsync<Response>(
"DeleteIndex",
async () =>
{
try
{
return await this._searchIndexClient.DeleteIndexAsync(this.Name, cancellationToken).ConfigureAwait(false);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
return null!;
}
});
}
/// <inheritdoc />
public override Task<TRecord?> GetAsync(TKey key, RecordRetrievalOptions? options = default, CancellationToken cancellationToken = default)
{
// Create Options.
var innerOptions = this.ConvertGetDocumentOptions(options);
var includeVectors = options?.IncludeVectors ?? false;
if (includeVectors && this._model.EmbeddingGenerationRequired)
{
throw new NotSupportedException(VectorDataStrings.IncludeVectorsNotSupportedWithEmbeddingGeneration);
}
// Get record.
return this.GetDocumentAndMapToDataModelAsync(key, includeVectors, innerOptions, cancellationToken);
}
/// <inheritdoc />
public override async IAsyncEnumerable<TRecord> GetAsync(IEnumerable<TKey> keys, RecordRetrievalOptions? options = default, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Verify.NotNull(keys);
// Create Options
var innerOptions = this.ConvertGetDocumentOptions(options);
var includeVectors = options?.IncludeVectors ?? false;
if (includeVectors && this._model.EmbeddingGenerationRequired)
{
throw new NotSupportedException(VectorDataStrings.IncludeVectorsNotSupportedWithEmbeddingGeneration);
}
foreach (var key in keys)
{
var record = await this.GetDocumentAndMapToDataModelAsync(key, includeVectors, innerOptions, cancellationToken).ConfigureAwait(false);
if (record is not null)
{
yield return record;
}
}
}
/// <inheritdoc />
public override Task DeleteAsync(TKey key, CancellationToken cancellationToken = default)
{
var stringKey = GetStringKey(key);
// Remove record.
return this.RunOperationAsync(
"DeleteDocuments",
() => this._searchClient.DeleteDocumentsAsync(this._model.KeyProperty.StorageName, [stringKey], new IndexDocumentsOptions(), cancellationToken));
}
/// <inheritdoc />
public override Task DeleteAsync(IEnumerable<TKey> keys, CancellationToken cancellationToken = default)
{
Verify.NotNull(keys);
if (!keys.Any())
{
return Task.CompletedTask;
}
var stringKeys = keys is IEnumerable<string> k ? k : keys.Select(GetStringKey);
// Remove records.
return this.RunOperationAsync(
"DeleteDocuments",
() => this._searchClient.DeleteDocumentsAsync(this._model.KeyProperty.StorageName, stringKeys, new IndexDocumentsOptions(), cancellationToken));
}
/// <inheritdoc />
public override async Task UpsertAsync(TRecord record, CancellationToken cancellationToken = default)
{
Verify.NotNull(record);
// Create options.
var innerOptions = new IndexDocumentsOptions { ThrowOnAnyError = true };
// Upsert record.
await this.MapToStorageModelAndUploadDocumentAsync([record], innerOptions, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task UpsertAsync(IEnumerable<TRecord> records, CancellationToken cancellationToken = default)
{
Verify.NotNull(records);
if (!records.Any())
{
return;
}
// Create Options
var innerOptions = new IndexDocumentsOptions { ThrowOnAnyError = true };
// Upsert records
await this.MapToStorageModelAndUploadDocumentAsync(records, innerOptions, cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public override IAsyncEnumerable<TRecord> GetAsync(Expression<Func<TRecord, bool>> filter, int top,
FilteredRecordRetrievalOptions<TRecord>? options = null, CancellationToken cancellationToken = default)
{
Verify.NotNull(filter);
Verify.NotLessThan(top, 1);
options ??= new();
var includeVectors = options.IncludeVectors;
if (includeVectors && this._model.EmbeddingGenerationRequired)
{
throw new NotSupportedException(VectorDataStrings.IncludeVectorsNotSupportedWithEmbeddingGeneration);
}
SearchOptions searchOptions = new()
{
VectorSearch = new(),
Size = top,
Skip = options.Skip,
Filter = new AzureAISearchFilterTranslator().Translate(filter, this._model)
};
// Filter out vector fields if requested.
if (!options.IncludeVectors)
{
searchOptions.Select.Add(this._model.KeyProperty.StorageName);
foreach (var dataProperty in this._model.DataProperties)
{
searchOptions.Select.Add(dataProperty.StorageName);
}
}
if (options.OrderBy is not null)
{
foreach (var pair in options.OrderBy(new()).Values)
{
PropertyModel property = this._model.GetDataOrKeyProperty(pair.PropertySelector);
string name = property.StorageName;
// From https://learn.microsoft.com/dotnet/api/azure.search.documents.searchoptions.orderby:
// "Each expression can be followed by asc to indicate ascending, or desc to indicate descending".
// "The default is ascending order."
if (!pair.Ascending)
{
name += " desc";
}
searchOptions.OrderBy.Add(name);
}
}
return this.SearchAndMapToDataModelAsync(null, searchOptions, options.IncludeVectors, cancellationToken)
.Select(result => result.Record);
}
#region Search
/// <inheritdoc />
public override async IAsyncEnumerable<VectorSearchResult<TRecord>> SearchAsync<TInput>(
TInput searchValue,
int top,
VectorSearchOptions<TRecord>? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Verify.NotNull(searchValue);
Verify.NotLessThan(top, 1);
options ??= s_defaultVectorSearchOptions;
var vectorProperty = this._model.GetVectorPropertyOrSingle(options);
var floatVector = await GetSearchVectorAsync(searchValue, vectorProperty, cancellationToken).ConfigureAwait(false);
var searchOptions = BuildSearchOptions(
this._model,
options,
top,
floatVector is null
? new VectorizableTextQuery((string)(object)searchValue) { KNearestNeighborsCount = top + options.Skip, Fields = { vectorProperty.StorageName } }
: new VectorizedQuery(floatVector.Value) { KNearestNeighborsCount = top + options.Skip, Fields = { vectorProperty.StorageName } });
await foreach (var record in this.SearchAndMapToDataModelAsync(null, searchOptions, options.IncludeVectors, cancellationToken).ConfigureAwait(false))
{
// Azure AI Search threshold filtering is in preview:
// https://learn.microsoft.com/azure/search/vector-search-how-to-query#set-thresholds-to-exclude-low-scoring-results-preview
// See https://github.com/microsoft/semantic-kernel/issues/13500.
// For now, perform post-filtering on the client-side.
if (options.ScoreThreshold.HasValue && record.Score < options.ScoreThreshold.Value)
{
continue;
}
yield return record;
}
}
/// <inheritdoc />
public async IAsyncEnumerable<VectorSearchResult<TRecord>> HybridSearchAsync<TInput>(
TInput searchValue,
ICollection<string> keywords,
int top,
HybridSearchOptions<TRecord>? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
where TInput : notnull
{
Verify.NotNull(keywords);
Verify.NotLessThan(top, 1);
// Resolve options.
options ??= s_defaultKeywordVectorizedHybridSearchOptions;
var vectorProperty = this._model.GetVectorPropertyOrSingle<TRecord>(new() { VectorProperty = options.VectorProperty });
var floatVector = await GetSearchVectorAsync(searchValue, vectorProperty, cancellationToken).ConfigureAwait(false);
var textDataProperty = this._model.GetFullTextDataPropertyOrSingle(options.AdditionalProperty);
// Build search options.
var searchOptions = BuildSearchOptions(
this._model,
new()
{
Filter = options.Filter,
VectorProperty = options.VectorProperty,
Skip = options.Skip,
},
top,
floatVector is null
? new VectorizableTextQuery((string)(object)searchValue) { KNearestNeighborsCount = top + options.Skip, Fields = { vectorProperty.StorageName } }
: new VectorizedQuery(floatVector.Value) { KNearestNeighborsCount = top + options.Skip, Fields = { vectorProperty.StorageName } });
searchOptions.SearchFields.Add(textDataProperty.StorageName);
var keywordsCombined = string.Join(" ", keywords);
await foreach (var record in this.SearchAndMapToDataModelAsync(keywordsCombined, searchOptions, options.IncludeVectors, cancellationToken).ConfigureAwait(false))
{
// Azure AI Search returns scores where higher values indicate more relevant results.
if (options.ScoreThreshold.HasValue && record.Score < options.ScoreThreshold.Value)
{
continue;
}
yield return record;
}
}
private static async ValueTask<ReadOnlyMemory<float>?> GetSearchVectorAsync<TInput>(TInput searchValue, VectorPropertyModel vectorProperty, CancellationToken cancellationToken)
where TInput : notnull
=> searchValue switch
{
ReadOnlyMemory<float> r => r,
float[] f => new ReadOnlyMemory<float>(f),
Embedding<float> e => e.Vector,
_ when vectorProperty.EmbeddingGenerationDispatcher is not null
=> ((Embedding<float>)await vectorProperty.GenerateEmbeddingAsync(searchValue, cancellationToken).ConfigureAwait(false)).Vector,
// A string was passed without an embedding generator being configured; send the string to Azure AI Search for backend embedding generation.
string when vectorProperty.EmbeddingGenerator is null => (ReadOnlyMemory<float>?)null,
_ => vectorProperty.EmbeddingGenerator is null
? throw new NotSupportedException(VectorDataStrings.InvalidSearchInputAndNoEmbeddingGeneratorWasConfigured(searchValue.GetType(), AzureAISearchModelBuilder.SupportedVectorTypes))
: throw new InvalidOperationException(VectorDataStrings.IncompatibleEmbeddingGeneratorWasConfiguredForInputType(typeof(TInput), vectorProperty.EmbeddingGenerator.GetType()))
};
#endregion Search
/// <inheritdoc />
public override object? GetService(Type serviceType, object? serviceKey = null)
{
Verify.NotNull(serviceType);
return
serviceKey is not null ? null :
serviceType == typeof(VectorStoreCollectionMetadata) ? this._collectionMetadata :
serviceType == typeof(SearchIndexClient) ? this._searchIndexClient :
serviceType == typeof(SearchClient) ? this._searchClient :
serviceType.IsInstanceOfType(this) ? this :
null;
}
/// <summary>
/// Get the document with the given key and map it to the data model using the configured mapper type.
/// </summary>
/// <param name="key">The key of the record to get.</param>
/// <param name="includeVectors">A value indicating whether to include vectors in the result or not.</param>
/// <param name="innerOptions">The Azure AI Search sdk options for getting a document.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>The retrieved document, mapped to the consumer data model.</returns>
private async Task<TRecord?> GetDocumentAndMapToDataModelAsync(
TKey key,
bool includeVectors,
GetDocumentOptions innerOptions,
CancellationToken cancellationToken)
{
const string OperationName = "GetDocument";
var stringKey = GetStringKey(key);
var jsonObject = await this.RunOperationAsync(
OperationName,
() => this.GetDocumentWithNotFoundHandlingAsync<JsonObject>(this._searchClient, stringKey, innerOptions, cancellationToken)).ConfigureAwait(false);
if (jsonObject is null)
{
return default;
}
return (TRecord)(object)this._mappper!.MapFromStorageToDataModel(jsonObject, includeVectors);
}
/// <summary>
/// Search for the documents matching the given options and map them to the data model using the configured mapper type.
/// </summary>
/// <param name="searchText">Text to use if doing a hybrid search. Null for non-hybrid search.</param>
/// <param name="searchOptions">The options controlling the behavior of the search operation.</param>
/// <param name="includeVectors">A value indicating whether to include vectors in the result or not.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>The mapped search results.</returns>
private async IAsyncEnumerable<VectorSearchResult<TRecord>> SearchAndMapToDataModelAsync(
string? searchText,
SearchOptions searchOptions,
bool includeVectors,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
const string OperationName = "Search";
var jsonObjectResults = await this.RunOperationAsync(
OperationName,
() => this._searchClient.SearchAsync<JsonObject>(searchText, searchOptions, cancellationToken)).ConfigureAwait(false);
await foreach (var result in this.MapSearchResultsAsync(jsonObjectResults.Value.GetResultsAsync(), OperationName, includeVectors).ConfigureAwait(false))
{
yield return result;
}
}
/// <summary>
/// Map the data model to the storage model and upload the document.
/// </summary>
/// <param name="records">The records to upload.</param>
/// <param name="innerOptions">The Azure AI Search sdk options for uploading a document.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>The document upload result.</returns>
private async Task<Response<IndexDocumentsResult>> MapToStorageModelAndUploadDocumentAsync(
IEnumerable<TRecord> records,
IndexDocumentsOptions innerOptions,
CancellationToken cancellationToken)
{
const string OperationName = "UploadDocuments";
(records, var generatedEmbeddings) = await ProcessEmbeddingsAsync(this._model, records, cancellationToken).ConfigureAwait(false);
// Handle auto-generated keys (client-side for Azure AI Search, which doesn't support server-side auto-generation)
var keyProperty = this._model.KeyProperty;
var jsonObjects = new List<JsonObject>();
var recordIndex = 0;
foreach (var record in records)
{
if (keyProperty.IsAutoGenerated && keyProperty.GetValue<Guid>(record) == Guid.Empty)
{
keyProperty.SetValue(record, Guid.NewGuid());
}
jsonObjects.Add(this._mappper!.MapFromDataToStorageModel(record, recordIndex++, generatedEmbeddings));
}
return await this.RunOperationAsync(
OperationName,
() => this._searchClient.UploadDocumentsAsync<JsonObject>(jsonObjects, innerOptions, cancellationToken)).ConfigureAwait(false);
}
/// <summary>
/// Map the search results from <see cref="SearchResult{JsonObject}"/> to <see cref="VectorSearchResult{TRecord}"/> objects using the configured mapper type.
/// </summary>
/// <param name="results">The search results to map.</param>
/// <param name="operationName">The name of the current operation for telemetry purposes.</param>
/// <param name="includeVectors">A value indicating whether to include vectors in the resultset or not.</param>
/// <returns>The mapped results.</returns>
private async IAsyncEnumerable<VectorSearchResult<TRecord>> MapSearchResultsAsync(IAsyncEnumerable<SearchResult<JsonObject>> results, string operationName, bool includeVectors)
{
await foreach (var result in results.ConfigureAwait(false))
{
var document = (TRecord)(object)this._mappper!.MapFromStorageToDataModel(result.Document, includeVectors);
yield return new VectorSearchResult<TRecord>(document, result.Score);
}
}
/// <summary>
/// Map the search results from <see cref="SearchResult{TRecord}"/> to <see cref="VectorSearchResult{TRecord}"/> objects.
/// </summary>
/// <param name="results">The search results to map.</param>
/// <returns>The mapped results.</returns>
private async IAsyncEnumerable<VectorSearchResult<TRecord>> MapSearchResultsAsync(IAsyncEnumerable<SearchResult<TRecord>> results)
{
await foreach (var result in results.ConfigureAwait(false))
{
yield return new VectorSearchResult<TRecord>(result.Document, result.Score);
}
}
/// <summary>
/// Convert the public <see cref="RecordRetrievalOptions"/> options model to the Azure AI Search <see cref="GetDocumentOptions"/> options model.
/// </summary>
/// <param name="options">The public options model.</param>
/// <returns>The Azure AI Search options model.</returns>
private GetDocumentOptions ConvertGetDocumentOptions(RecordRetrievalOptions? options)
{
var innerOptions = new GetDocumentOptions();
if (options?.IncludeVectors is not true)
{
innerOptions.SelectedFields.Add(this._model.KeyProperty.StorageName);
foreach (var dataProperty in this._model.DataProperties)
{
innerOptions.SelectedFields.Add(dataProperty.StorageName);
}
}
return innerOptions;
}
/// <summary>
/// Build the search options for a vector search, where the type of vector search can be provided as input.
/// E.g. VectorizedQuery or VectorizableTextQuery.
/// </summary>
private static SearchOptions BuildSearchOptions(CollectionModel model, VectorSearchOptions<TRecord> options, int top, VectorQuery? vectorQuery)
{
if (model.VectorProperties.Count == 0)
{
throw new InvalidOperationException("The collection does not have any vector fields, so vector search is not possible.");
}
if (options.IncludeVectors && model.EmbeddingGenerationRequired)
{
throw new NotSupportedException(VectorDataStrings.IncludeVectorsNotSupportedWithEmbeddingGeneration);
}
// Build filter object.
var filter = options.Filter is not null
? new AzureAISearchFilterTranslator().Translate(options.Filter, model)
: null;
// Build search options.
var searchOptions = new SearchOptions
{
VectorSearch = new(),
Size = top,
Skip = options.Skip,
};
if (filter is not null)
{
searchOptions.Filter = filter;
}
searchOptions.VectorSearch.Queries.Add(vectorQuery);
// Filter out vector fields if requested.
if (!options.IncludeVectors)
{
searchOptions.Select.Add(model.KeyProperty.StorageName);
foreach (var dataProperty in model.DataProperties)
{
searchOptions.Select.Add(dataProperty.StorageName);
}
}
return searchOptions;
}
private static async ValueTask<(IEnumerable<TRecord> records, IReadOnlyList<MEAI.Embedding>?[]?)> ProcessEmbeddingsAsync(
CollectionModel model,
IEnumerable<TRecord> records,
CancellationToken cancellationToken)
{
IReadOnlyList<TRecord>? recordsList = null;
// If an embedding generator is defined, invoke it once per property for all records.
IReadOnlyList<MEAI.Embedding>?[]? generatedEmbeddings = null;
var vectorPropertyCount = model.VectorProperties.Count;
for (var i = 0; i < vectorPropertyCount; i++)
{
var vectorProperty = model.VectorProperties[i];
if (AzureAISearchModelBuilder.IsVectorPropertyTypeValidCore(vectorProperty.Type, out _))
{
continue;
}
// We have a vector property whose type isn't natively supported - we need to generate embeddings.
Debug.Assert(vectorProperty.EmbeddingGenerator is not null);
// We have a property with embedding generation; materialize the records' enumerable if needed, to
// prevent multiple enumeration.
if (recordsList is null)
{
recordsList = records is IReadOnlyList<TRecord> r ? r : records.ToList();
if (recordsList.Count == 0)
{
return (records, null);
}
records = recordsList;
}
// TODO: Ideally we'd group together vector properties using the same generator (and with the same input and output properties),
// and generate embeddings for them in a single batch. That's some more complexity though.
generatedEmbeddings ??= new IReadOnlyList<MEAI.Embedding>?[vectorPropertyCount];
generatedEmbeddings[i] = await vectorProperty.GenerateEmbeddingsAsync(records.Select(r => vectorProperty.GetValueAsObject(r)), cancellationToken).ConfigureAwait(false);
}
return (records, generatedEmbeddings);
}
/// <summary>
/// Get a document with the given key, and return null if it is not found.
/// </summary>
/// <typeparam name="T">The type to deserialize the document to.</typeparam>
/// <param name="searchClient">The search client to use when fetching the document.</param>
/// <param name="key">The key of the record to get.</param>
/// <param name="innerOptions">The Azure AI Search sdk options for getting a document.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>The retrieved document, mapped to the consumer data model, or null if not found.</returns>
private async Task<T?> GetDocumentWithNotFoundHandlingAsync<T>(
SearchClient searchClient,
string key,
GetDocumentOptions innerOptions,
CancellationToken cancellationToken)
{
const string OperationName = "GetDocument";
try
{
return await searchClient.GetDocumentAsync<T>(key, innerOptions, cancellationToken).ConfigureAwait(false);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
return default;
}
catch (AggregateException ex) when (ex.InnerException is RequestFailedException innerEx)
{
throw new VectorStoreException("Call to vector store failed.", ex)
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = this._collectionMetadata.VectorStoreName,
CollectionName = this.Name,
OperationName = OperationName
};
}
catch (RequestFailedException ex)
{
throw new VectorStoreException("Call to vector store failed.", ex)
{
VectorStoreSystemName = AzureAISearchConstants.VectorStoreSystemName,
VectorStoreName = this._collectionMetadata.VectorStoreName,
CollectionName = this.Name,
OperationName = OperationName
};
}
}
/// <summary>
/// Run the given operation and wrap any <see cref="RequestFailedException"/> with <see cref="VectorStoreException"/>."/>
/// </summary>
/// <typeparam name="T">The response type of the operation.</typeparam>
/// <param name="operationName">The type of database operation being run.</param>
/// <param name="operation">The operation to run.</param>
/// <returns>The result of the operation.</returns>
private Task<T> RunOperationAsync<T>(string operationName, Func<Task<T>> operation) =>
VectorStoreErrorHandler.RunOperationAsync<T, RequestFailedException>(
this._collectionMetadata,
operationName,
operation);
private static string GetStringKey(TKey key)
{
Verify.NotNull(key);
var stringKey = key switch
{
string s => s,
Guid g => g.ToString(),
_ => throw new UnreachableException("string key should have been validated during model building")
};
Verify.NotNullOrWhiteSpace(stringKey, nameof(key));
return stringKey;
}
}