-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEmulatorIntegrationTests.cs
More file actions
856 lines (714 loc) · 32.5 KB
/
Copy pathEmulatorIntegrationTests.cs
File metadata and controls
856 lines (714 loc) · 32.5 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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Azure.Search.Documents.Models;
using Xunit;
namespace AzureSearchEmulator.IntegrationTests;
/// <summary>
/// Integration tests for the Azure Search Emulator using the Azure Search SDK.
/// Tests run against a containerized instance of the emulator using Testcontainers.
/// Covers index creation, document indexing, and search/retrieval operations using a product e-commerce domain.
/// </summary>
public class EmulatorIntegrationTests(EmulatorFactory factory)
: IClassFixture<EmulatorFactory>
{
[Fact]
public async Task CreateIndex_ShouldSucceed()
{
// Arrange
const string indexName = "test-create-index";
var indexClient = factory.CreateSearchIndexClient();
// Act
var result = await CreateIndexAsync(indexClient, indexName);
// Assert
Assert.NotNull(result);
Assert.Equal(indexName, result.Name);
// Verify the index exists
var retrievedIndex = await indexClient.GetIndexAsync(indexName);
Assert.NotNull(retrievedIndex);
Assert.Equal(indexName, retrievedIndex.Value.Name);
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task UploadDocuments_ShouldSucceed()
{
const string indexName = "test-upload-documents";
var indexClient = factory.CreateSearchIndexClient();
// Arrange - Create index first
await CreateIndexAsync(indexClient, indexName);
var documents = CreateProductDocuments();
// Act
var searchClient = factory.CreateSearchClient(indexName);
var batch = IndexDocumentsBatch.Upload(documents);
var result = await searchClient.IndexDocumentsAsync(batch);
// Assert
Assert.NotNull(result);
Assert.True(result.Value.Results.All(r => r.Succeeded), "All documents should be successfully indexed");
// Verify document count
var countResult = await searchClient.GetDocumentCountAsync();
Assert.Equal(5, countResult.Value);
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task GetDocumentById_ShouldReturnDocument()
{
const string indexName = "test-get-document";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act
var document = await searchClient.GetDocumentAsync<Product>("1");
// Assert
Assert.NotNull(document);
Assert.Equal("1", document.Value.Id);
Assert.Equal("Laptop Pro 15", document.Value.Name);
Assert.Equal("High-performance laptop with 16GB RAM and 512GB SSD", document.Value.Description);
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SimpleQuery_ShouldReturnResults()
{
const string indexName = "test-simple-search";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act
var options = new SearchOptions
{
SearchFields = { "name", "description" },
Size = 50
};
var results = await searchClient.SearchAsync<Product>("laptop", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.Contains(items, r => r.Document.Name.Contains("Laptop", StringComparison.OrdinalIgnoreCase));
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_WithFilter_ShouldReturnResults()
{
const string indexName = "test-filter-search";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Filter by inStock field
var options = new SearchOptions
{
Filter = "InStock eq true",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => r.Document.InStock), "All results should have inStock = true");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_WithFilter_OnSearchableStringField_ShouldReturnResults()
{
// Regression test for issue #27: filtering a Searchable+Filterable string field
// must work. Before the fix, the analyzer lowercased 'Electronics' at index time
// and the exact TermQuery at filter time found zero hits.
const string indexName = "test-filter-searchable-string";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
var options = new SearchOptions
{
Filter = "Category eq 'Electronics'",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
Assert.NotNull(results);
var items = await results.Value.GetResultsAsync().ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => r.Document.Category == "Electronics"),
"All results should have Category = Electronics");
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchOnDualIndexedField_StillMatchesAnalyzedTokens()
{
// Dual-indexing (TextField + StringField under same name) must not break
// full-text search: a tokenized search for 'electronics' must still match.
const string indexName = "test-search-on-dual-indexed";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
var options = new SearchOptions { SearchFields = { "Category" }, Size = 50 };
var results = await searchClient.SearchAsync<Product>("electronics", options);
var items = await results.Value.GetResultsAsync().ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => r.Document.Category == "Electronics"));
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_FilterOnNonFilterableField_ShouldError()
{
// Azure rejects $filter against a non-filterable field; the emulator should too.
const string indexName = "test-filter-nonfilterable";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
var index = new SearchIndex(indexName)
{
Fields =
[
new SearchField(nameof(Product.Id), SearchFieldDataType.String) { IsKey = true, IsStored = true, IsSearchable = true, IsFilterable = true },
new SearchField(nameof(Product.Name), SearchFieldDataType.String) { IsSearchable = true, IsFilterable = false, IsStored = true },
new SearchField(nameof(Product.Description), SearchFieldDataType.String) { IsSearchable = true, IsStored = true },
new SearchField(nameof(Product.Price), SearchFieldDataType.Double) { IsFilterable = true, IsSortable = true, IsStored = true },
new SearchField(nameof(Product.Category), SearchFieldDataType.String) { IsSearchable = true, IsFilterable = true, IsStored = true },
new SearchField(nameof(Product.InStock), SearchFieldDataType.Boolean) { IsFilterable = true, IsStored = true }
]
};
await indexClient.CreateIndexAsync(index);
await UploadDocumentsAsync(searchClient);
var options = new SearchOptions { Filter = "Name eq 'Laptop Pro 15'", Size = 50 };
await Assert.ThrowsAnyAsync<Exception>(async () =>
{
var results = await searchClient.SearchAsync<Product>("*", options);
await results.Value.GetResultsAsync().ToListAsync();
});
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_WithSorting_ShouldReturnSortedResults()
{
const string indexName = "test-sort-search";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Sort by price descending
var options = new SearchOptions
{
OrderBy = { "price desc" },
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
// Verify descending order
double? previousPrice = null;
foreach (var item in items)
{
if (previousPrice.HasValue)
{
Assert.True(item.Document.Price <= previousPrice, "Results should be sorted by price descending");
}
previousPrice = item.Document.Price;
}
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_WithPaging_ShouldReturnPagedResults()
{
const string indexName = "test-paging-search";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Get first page
var firstPageOptions = new SearchOptions
{
Size = 2,
Skip = 0
};
var firstPageResults = await searchClient.SearchAsync<Product>("*:*", firstPageOptions);
var firstPageItems = await firstPageResults.Value.GetResultsAsync().ToListAsync();
// Assert first page
Assert.NotNull(firstPageItems);
Assert.Equal(2, firstPageItems.Count);
var firstPageId = firstPageItems[0].Document.Id;
// Act - Get second page
var secondPageOptions = new SearchOptions
{
Size = 2,
Skip = 2
};
var secondPageResults = await searchClient.SearchAsync<Product>("*", secondPageOptions);
var secondPageItems = await secondPageResults.Value.GetResultsAsync().ToListAsync();
// Assert second page
Assert.NotNull(secondPageItems);
Assert.Equal(2, secondPageItems.Count);
var secondPageId = secondPageItems[0].Document.Id;
// Verify different pages
Assert.NotEqual(firstPageId, secondPageId);
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task CreateOrUpdateIndex_WhenIndexDoesNotExist_ShouldCreate()
{
// Arrange
const string indexName = "test-createorupdate-create";
var indexClient = factory.CreateSearchIndexClient();
// Ensure a clean slate
try
{
await indexClient.DeleteIndexAsync(indexName);
}
catch (Azure.RequestFailedException ex) when (ex.Status == 404)
{
// expected
}
var index = new SearchIndex(indexName)
{
Fields =
[
new SearchField(nameof(Product.Id), SearchFieldDataType.String) { IsKey = true, IsStored = true, IsSearchable = true, IsFilterable = true },
new SearchField(nameof(Product.Name), SearchFieldDataType.String) { IsSearchable = true, IsStored = true }
]
};
// Act - PUT to a non-existent index should create it
var result = await indexClient.CreateOrUpdateIndexAsync(index);
// Assert
Assert.NotNull(result);
Assert.Equal(indexName, result.Value.Name);
var retrieved = await indexClient.GetIndexAsync(indexName);
Assert.NotNull(retrieved);
Assert.Equal(indexName, retrieved.Value.Name);
Assert.Equal(2, retrieved.Value.Fields.Count);
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task CreateOrUpdateIndex_WhenIndexExists_ShouldUpdateSchema()
{
// Arrange
const string indexName = "test-createorupdate-update";
var indexClient = factory.CreateSearchIndexClient();
await CreateIndexAsync(indexClient, indexName);
// Pull the current index and add a backward-compatible field
var existing = (await indexClient.GetIndexAsync(indexName)).Value;
var originalFieldCount = existing.Fields.Count;
existing.Fields.Add(new SearchField("Tags", SearchFieldDataType.String) { IsFilterable = true, IsStored = true });
// Act - PUT on an existing index should update its schema
var result = await indexClient.CreateOrUpdateIndexAsync(existing);
// Assert
Assert.NotNull(result);
Assert.Equal(indexName, result.Value.Name);
var retrieved = await indexClient.GetIndexAsync(indexName);
Assert.Equal(originalFieldCount + 1, retrieved.Value.Fields.Count);
Assert.Contains(retrieved.Value.Fields, f => f.Name == "Tags");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task DeleteIndex_ShouldSucceed()
{
const string indexName = "test-delete-index";
var indexClient = factory.CreateSearchIndexClient();
// Arrange - Create index first
await CreateIndexAsync(indexClient, indexName);
// Act
await indexClient.DeleteIndexAsync(indexName);
// Assert - Verify index is deleted
var exception = await Assert.ThrowsAsync<Azure.RequestFailedException>(
async () => await indexClient.GetIndexAsync(indexName)
);
Assert.Equal(404, exception.Status);
}
[Fact]
public async Task SearchDocuments_SearchIsMatch_BasicQuery_ShouldReturnResults()
{
const string indexName = "test-ismatch-basic";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Use search.ismatch to search for 'laptop' in all searchable fields
var options = new SearchOptions
{
Filter = "search.ismatch('laptop')",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.Any(r => r.Document.Name.Contains("Laptop", StringComparison.OrdinalIgnoreCase)),
"Should return documents with 'laptop' in Name or Description");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchIsMatch_WithFieldName_ShouldReturnResults()
{
const string indexName = "test-ismatch-field";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Search in specific field using search.ismatch(search, field)
var options = new SearchOptions
{
Filter = "search.ismatch('laptop', 'Name')",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => r.Document.Name.Contains("Laptop", StringComparison.OrdinalIgnoreCase)),
"All results should have 'laptop' in Name field");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchIsMatch_WithMultipleFields_ShouldReturnResults()
{
const string indexName = "test-ismatch-multi-field";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Search in multiple fields using search.ismatch(search, fields)
var options = new SearchOptions
{
Filter = "search.ismatch('16000 DPI', 'Name,Description')",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.Contains(items, r => r.Document.Name == "Gaming Mouse" || r.Document.Description.Contains("16000 DPI"));
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchIsMatch_WithBooleanOperator_ShouldReturnResults()
{
const string indexName = "test-ismatch-and";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Combine search.ismatch with other filters using AND
var options = new SearchOptions
{
Filter = "search.ismatch('laptop') and InStock eq true",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => r.Document.InStock), "All results should have InStock = true");
Assert.True(items.All(r => r.Document.Name.Contains("Laptop", StringComparison.OrdinalIgnoreCase) ||
r.Document.Description.Contains("Laptop", StringComparison.OrdinalIgnoreCase)),
"All results should contain 'laptop'");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchIsMatch_WithNegation_ShouldReturnResults()
{
const string indexName = "test-ismatch-not";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Use NOT to exclude search.ismatch results
var options = new SearchOptions
{
Filter = "not search.ismatch('keyboard')",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.All(r => !r.Document.Name.Contains("Keyboard", StringComparison.OrdinalIgnoreCase) &&
!r.Document.Description.Contains("Keyboard", StringComparison.OrdinalIgnoreCase)),
"All results should NOT contain 'keyboard'");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task SearchDocuments_SearchIsMatchScoring_ShouldReturnResults()
{
const string indexName = "test-ismatchscoring";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
// Arrange - Create index and upload documents
await CreateIndexAsync(indexClient, indexName);
await UploadDocumentsAsync(searchClient);
// Act - Use search.ismatchscoring (scoring variant)
var options = new SearchOptions
{
Filter = "search.ismatchscoring('laptop')",
Size = 50
};
var results = await searchClient.SearchAsync<Product>("*", options);
// Assert
Assert.NotNull(results);
var resultsList = results.Value.GetResultsAsync();
var items = await resultsList.ToListAsync();
Assert.NotEmpty(items);
Assert.True(items.Any(r => r.Document.Name.Contains("Laptop", StringComparison.OrdinalIgnoreCase)),
"Should return documents with 'laptop'");
// Cleanup
await indexClient.DeleteIndexAsync(indexName);
}
// Collection field tests (issue #6)
[Fact]
public async Task CollectionField_UploadAndGet_ReturnsArrayValues()
{
const string indexName = "test-collection-roundtrip";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
var doc = await searchClient.GetDocumentAsync<TaggedProduct>("1");
Assert.NotNull(doc.Value);
Assert.Equal("1", doc.Value.Id);
Assert.Equal(new[] { "red", "cotton", "shirt" }, doc.Value.Tags);
Assert.Equal(new[] { 8, 10, 12 }, doc.Value.Sizes);
await indexClient.DeleteIndexAsync(indexName);
}
[Fact]
public async Task CollectionField_FilterAnyEqual_ReturnsMatchingDocuments()
{
const string indexName = "test-collection-any-eq";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
var options = new SearchOptions { Filter = "Tags/any(t: t eq 'cotton')", Size = 50 };
var results = await searchClient.SearchAsync<TaggedProduct>("*", options);
var ids = (await results.Value.GetResultsAsync().ToListAsync())
.Select(r => r.Document.Id)
.OrderBy(id => id)
.ToList();
// Doc 1 (Red Shirt) and doc 4 (Green Socks) both have 'cotton' in their tags.
Assert.Equal(["1", "4"], ids);
}
[Fact]
public async Task CollectionField_FilterAnySearchIn_ReturnsMatchingDocuments()
{
const string indexName = "test-collection-any-searchin";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
var options = new SearchOptions { Filter = "Tags/any(t: search.in(t, 'wool,denim'))", Size = 50 };
var results = await searchClient.SearchAsync<TaggedProduct>("*", options);
var ids = (await results.Value.GetResultsAsync().ToListAsync())
.Select(r => r.Document.Id)
.OrderBy(id => id)
.ToList();
Assert.Equal(["2", "3"], ids);
}
[Fact]
public async Task CollectionField_FilterAllNotEqual_ExcludesDocsContainingValue()
{
const string indexName = "test-collection-all-ne";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
// all(t: t ne 'cotton') — only docs whose tags do NOT contain 'cotton' should match.
// Doc 1 and doc 4 contain 'cotton', so only doc 2 (jeans) and doc 3 (hat) should match.
var options = new SearchOptions { Filter = "Tags/all(t: t ne 'cotton')", Size = 50 };
var results = await searchClient.SearchAsync<TaggedProduct>("*", options);
var ids = (await results.Value.GetResultsAsync().ToListAsync())
.Select(r => r.Document.Id)
.OrderBy(id => id)
.ToList();
Assert.Equal(["2", "3"], ids);
}
[Fact]
public async Task CollectionField_FilterAnyNumericRange_MatchesDocsWithAnyValueInRange()
{
const string indexName = "test-collection-any-numeric";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
// Doc 1 has Sizes [8,10,12] — 12 is >= 12. Doc 2 has Sizes [30,32,34] — all >= 12.
var options = new SearchOptions { Filter = "Sizes/any(s: s ge 12)", Size = 50 };
var results = await searchClient.SearchAsync<TaggedProduct>("*", options);
var ids = (await results.Value.GetResultsAsync().ToListAsync())
.Select(r => r.Document.Id)
.OrderBy(id => id)
.ToList();
Assert.Equal(["1", "2"], ids);
}
[Fact]
public async Task CollectionField_FullTextSearchOnSearchableCollection_MatchesAcrossElements()
{
const string indexName = "test-collection-fulltext";
var indexClient = factory.CreateSearchIndexClient();
var searchClient = factory.CreateSearchClient(indexName);
await CreateTaggedProductIndexAsync(indexClient, indexName);
await UploadTaggedProductsAsync(searchClient);
// Tags is searchable; a free-text search for 'denim' should match doc 2 even though
// 'denim' is just one entry in its tags array.
var options = new SearchOptions { SearchFields = { "Tags" }, Size = 50 };
var results = await searchClient.SearchAsync<TaggedProduct>("denim", options);
var items = await results.Value.GetResultsAsync().ToListAsync();
Assert.Single(items);
Assert.Equal("2", items[0].Document.Id);
}
// Helper Methods
private static async Task<SearchIndex> CreateTaggedProductIndexAsync(SearchIndexClient indexClient, string indexName)
{
try
{
await indexClient.DeleteIndexAsync(indexName);
}
catch (Azure.RequestFailedException ex) when (ex.Status == 404)
{
// expected
}
var index = new SearchIndex(indexName)
{
Fields =
[
new SearchField(nameof(TaggedProduct.Id), SearchFieldDataType.String) { IsKey = true, IsStored = true, IsFilterable = true },
new SearchField(nameof(TaggedProduct.Name), SearchFieldDataType.String) { IsSearchable = true, IsStored = true },
new SearchField(nameof(TaggedProduct.Tags), SearchFieldDataType.Collection(SearchFieldDataType.String)) { IsSearchable = true, IsFilterable = true, IsStored = true },
new SearchField(nameof(TaggedProduct.Sizes), SearchFieldDataType.Collection(SearchFieldDataType.Int32)) { IsFilterable = true, IsStored = true }
]
};
await indexClient.CreateIndexAsync(index);
return index;
}
private static async Task UploadTaggedProductsAsync(SearchClient searchClient)
{
var documents = new List<TaggedProduct>
{
new() { Id = "1", Name = "Red Shirt", Tags = ["red", "cotton", "shirt"], Sizes = [8, 10, 12] },
new() { Id = "2", Name = "Blue Jeans", Tags = ["blue", "denim", "pants"], Sizes = [30, 32, 34] },
new() { Id = "3", Name = "Wool Hat", Tags = ["wool", "warm"], Sizes = [] },
new() { Id = "4", Name = "Green Socks", Tags = ["green", "cotton"], Sizes = [9, 10, 11] },
};
var batch = IndexDocumentsBatch.Upload(documents);
await searchClient.IndexDocumentsAsync(batch);
}
private static async Task<SearchIndex> CreateIndexAsync(SearchIndexClient indexClient, string indexName)
{
// Clean up any existing index
try
{
await indexClient.DeleteIndexAsync(indexName);
}
catch (Azure.RequestFailedException ex) when (ex.Status == 404)
{
// Index doesn't exist, which is fine
}
var index = new SearchIndex(indexName)
{
Fields =
[
new SearchField(nameof(Product.Id), SearchFieldDataType.String) { IsKey = true, IsStored = true, IsSearchable = true, IsFilterable = true},
new SearchField(nameof(Product.Name), SearchFieldDataType.String) { IsSearchable = true, IsStored = true },
new SearchField(nameof(Product.Description), SearchFieldDataType.String) { IsSearchable = true, IsStored = true},
new SearchField(nameof(Product.Price), SearchFieldDataType.Double) { IsFilterable = true, IsSortable = true, IsStored = true },
new SearchField(nameof(Product.Category), SearchFieldDataType.String) { IsSearchable = true, IsFilterable = true, IsStored = true },
new SearchField(nameof(Product.InStock), SearchFieldDataType.Boolean) { IsFilterable = true, IsStored = true }
]
};
await indexClient.CreateIndexAsync(index);
return index;
}
private static async Task UploadDocumentsAsync(SearchClient searchClient)
{
var documents = CreateProductDocuments();
var batch = IndexDocumentsBatch.Upload(documents);
await searchClient.IndexDocumentsAsync(batch);
}
private static List<Product> CreateProductDocuments()
{
return
[
new Product
{
Id = "1",
Name = "Laptop Pro 15",
Description = "High-performance laptop with 16GB RAM and 512GB SSD",
Price = 1299.99,
Category = "Electronics",
InStock = true
},
new Product
{
Id = "2",
Name = "Laptop Budget 13",
Description = "Affordable laptop perfect for students and everyday use",
Price = 499.99,
Category = "Electronics",
InStock = true
},
new Product
{
Id = "3",
Name = "Gaming Mouse",
Description = "Precision gaming mouse with 16000 DPI sensor",
Price = 59.99,
Category = "Accessories",
InStock = true
},
new Product
{
Id = "4",
Name = "Mechanical Keyboard",
Description = "Mechanical keyboard with Cherry MX switches and RGB lighting",
Price = 149.99,
Category = "Accessories",
InStock = false
},
new Product
{
Id = "5",
Name = "Monitor 4K",
Description = "27-inch 4K monitor with 60Hz refresh rate",
Price = 599.99,
Category = "Electronics",
InStock = true
}
];
}
}