-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
SearchClient.cs
2097 lines (2032 loc) · 89.1 KB
/
SearchClient.cs
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.Core.Serialization;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Models;
namespace Azure.Search.Documents
{
/// <summary>
/// Azure Cognitive Search client that can be used to query an index and
/// upload, merge, or delete documents.
/// </summary>
public class SearchClient
{
/// <summary>
/// Gets the URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// </summary>
/// <remarks>
/// This is not the URI of the Search Index. You could construct that
/// URI with "{Endpoint}/indexes/{IndexName}" if needed.
/// </remarks>
public virtual Uri Endpoint { get; }
/// <summary>
/// The name of the Search Service, lazily obtained from the
/// <see cref="Endpoint"/>.
/// </summary>
private string _serviceName;
/// <summary>
/// Gets the name of the Search Service.
/// </summary>
public virtual string ServiceName =>
_serviceName ??= Endpoint.GetSearchServiceName();
/// <summary>
/// Gets the name of the Search Index.
/// </summary>
public virtual string IndexName { get; }
/// <summary>
/// Gets an <see cref="ObjectSerializer"/> that can be used to
/// customize the serialization of strongly typed models.
/// </summary>
internal ObjectSerializer Serializer { get; }
/// <summary>
/// Gets the authenticated <see cref="HttpPipeline"/> used for sending
/// requests to the Search Service.
/// </summary>
private HttpPipeline Pipeline { get; }
/// <summary>
/// Gets the <see cref="Azure.Core.Pipeline.ClientDiagnostics"/> used
/// to provide tracing support for the client library.
/// </summary>
internal ClientDiagnostics ClientDiagnostics { get; }
/// <summary>
/// Gets the REST API version of the Search Service to use when making
/// requests.
/// </summary>
private SearchClientOptions.ServiceVersion Version { get; }
/// <summary>
/// Gets the generated document operations to make requests.
/// </summary>
private DocumentsRestClient Protocol { get; }
#region ctors
/// <summary>
/// Initializes a new instance of the SearchClient class for
/// mocking.
/// </summary>
protected SearchClient() { }
/// <summary>
/// Initializes a new instance of the SearchClient class for
/// querying an index and uploading, merging, or deleting documents.
/// </summary>
/// <param name="endpoint">
/// Required. The URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// The URI must use HTTPS.
/// </param>
/// <param name="indexName">
/// Required. The name of the Search Index.
/// </param>
/// <param name="credential">
/// Required. The API key credential used to authenticate requests
/// against the search service. You need to use an admin key to
/// modify the documents in a Search Index. See
/// <see href="https://docs.microsoft.com/azure/search/search-security-api-keys">Create and manage api-keys for an Azure Cognitive Search service</see>
/// for more information about API keys in Azure Cognitive Search.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="endpoint"/>,
/// <paramref name="indexName"/>, or <paramref name="credential"/> is
/// null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="endpoint"/> is not using HTTPS or
/// the <paramref name="indexName"/> is empty.
/// </exception>
public SearchClient(
Uri endpoint,
string indexName,
AzureKeyCredential credential) :
this(endpoint, indexName, credential, null)
{
}
/// <summary>
/// Initializes a new instance of the SearchClient class for
/// querying an index and uploading, merging, or deleting documents.
/// </summary>
/// <param name="endpoint">
/// Required. The URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// The URI must use HTTPS.
/// </param>
/// <param name="indexName">
/// Required. The name of the Search Index.
/// </param>
/// <param name="tokenCredential">
/// Required. The token credential used to authenticate requests against the Search service.
/// See <see href="https://docs.microsoft.com/azure/search/search-security-rbac">Use role-based authorization in Azure Cognitive Search</see> for
/// more information about role-based authorization in Azure Cognitive Search.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="endpoint"/>,
/// <paramref name="indexName"/>, or <paramref name="tokenCredential"/> is
/// null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="endpoint"/> is not using HTTPS or
/// the <paramref name="indexName"/> is empty.
/// </exception>
public SearchClient(
Uri endpoint,
string indexName,
TokenCredential tokenCredential) :
this(endpoint, indexName, tokenCredential, null)
{
}
/// <summary>
/// Initializes a new instance of the SearchClient class for
/// querying an index and uploading, merging, or deleting documents.
/// </summary>
/// <param name="endpoint">
/// Required. The URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// The URI must use HTTPS.
/// </param>
/// <param name="indexName">
/// Required. The name of the Search Index.
/// </param>
/// <param name="credential">
/// Required. The API key credential used to authenticate requests
/// against the search service. You need to use an admin key to
/// modify the documents in a Search Index. See
/// <see href="https://docs.microsoft.com/azure/search/search-security-api-keys">Create and manage api-keys for an Azure Cognitive Search service</see>
/// for more information about API keys in Azure Cognitive Search.
/// </param>
/// <param name="options">
/// Client configuration options for connecting to Azure Cognitive
/// Search.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="endpoint"/>,
/// <paramref name="indexName"/>, or <paramref name="credential"/> is
/// null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="endpoint"/> is not using HTTPS or
/// the <paramref name="indexName"/> is empty.
/// </exception>
public SearchClient(
Uri endpoint,
string indexName,
AzureKeyCredential credential,
SearchClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
endpoint.AssertHttpsScheme(nameof(endpoint));
Argument.AssertNotNullOrEmpty(indexName, nameof(indexName));
Argument.AssertNotNull(credential, nameof(credential));
options ??= new SearchClientOptions();
Endpoint = endpoint;
IndexName = indexName;
Serializer = options.Serializer;
ClientDiagnostics = new ClientDiagnostics(options);
Pipeline = options.Build(credential);
Version = options.Version;
Protocol = new DocumentsRestClient(
ClientDiagnostics,
Pipeline,
endpoint.AbsoluteUri,
indexName,
null,
Version.ToVersionString());
}
/// <summary>
/// Initializes a new instance of the SearchClient class for
/// querying an index and uploading, merging, or deleting documents.
/// </summary>
/// <param name="endpoint">
/// Required. The URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// The URI must use HTTPS.
/// </param>
/// <param name="indexName">
/// Required. The name of the Search Index.
/// </param>
/// <param name="tokenCredential">
/// Required. The token credential used to authenticate requests against the Search service.
/// See <see href="https://docs.microsoft.com/azure/search/search-security-rbac">Use role-based authorization in Azure Cognitive Search</see> for
/// more information about role-based authorization in Azure Cognitive Search.
/// </param>
/// <param name="options">
/// Client configuration options for connecting to Azure Cognitive
/// Search.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when the <paramref name="endpoint"/>,
/// <paramref name="indexName"/>, or <paramref name="tokenCredential"/> is
/// null.
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when the <paramref name="endpoint"/> is not using HTTPS or
/// the <paramref name="indexName"/> is empty.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "AZC0006:DO provide constructor overloads that allow specifying additional options.", Justification = "Avoid ambiguous method definition")]
public SearchClient(
Uri endpoint,
string indexName,
TokenCredential tokenCredential,
SearchClientOptions options)
{
Argument.AssertNotNull(endpoint, nameof(endpoint));
endpoint.AssertHttpsScheme(nameof(endpoint));
Argument.AssertNotNullOrEmpty(indexName, nameof(indexName));
Argument.AssertNotNull(tokenCredential, nameof(tokenCredential));
options ??= new SearchClientOptions();
Endpoint = endpoint;
IndexName = indexName;
Serializer = options.Serializer;
ClientDiagnostics = new ClientDiagnostics(options);
Pipeline = options.Build(tokenCredential);
Version = options.Version;
Protocol = new DocumentsRestClient(
ClientDiagnostics,
Pipeline,
endpoint.AbsoluteUri,
indexName,
null,
Version.ToVersionString());
}
/// <summary>
/// Initializes a new instance of the SearchClient class from a
/// <see cref="SearchIndexClient"/>.
/// </summary>
/// <param name="endpoint">
/// Required. The URI endpoint of the Search Service. This is likely
/// to be similar to "https://{search_service}.search.windows.net".
/// The URI must use HTTPS.
/// </param>
/// <param name="indexName">
/// Required. The name of the Search Index.
/// </param>
/// <param name="serializer">
/// An optional customized serializer to use for search documents.
/// </param>
/// <param name="pipeline">
/// The authenticated <see cref="HttpPipeline"/> used for sending
/// requests to the Search Service.
/// </param>
/// <param name="diagnostics">
/// The <see cref="Azure.Core.Pipeline.ClientDiagnostics"/> used to
/// provide tracing support for the client library.
/// </param>
/// <param name="version">
/// The REST API version of the Search Service to use when making
/// requests.
/// </param>
internal SearchClient(
Uri endpoint,
string indexName,
ObjectSerializer serializer,
HttpPipeline pipeline,
ClientDiagnostics diagnostics,
SearchClientOptions.ServiceVersion version)
{
Debug.Assert(endpoint != null);
Debug.Assert(string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
Debug.Assert(!string.IsNullOrEmpty(indexName));
Debug.Assert(pipeline != null);
Debug.Assert(diagnostics != null);
Debug.Assert(
SearchClientOptions.ServiceVersion.V2020_06_30 <= version &&
version <= SearchClientOptions.LatestVersion);
Endpoint = endpoint;
IndexName = indexName;
Serializer = serializer;
ClientDiagnostics = diagnostics;
Pipeline = pipeline;
Version = version;
Protocol = new DocumentsRestClient(
ClientDiagnostics,
Pipeline,
endpoint.AbsoluteUri,
IndexName,
null,
Version.ToVersionString());
}
/// <summary>
/// Get a SearchIndexClient with the same pipeline.
/// </summary>
/// <returns>A SearchIndexClient.</returns>
internal SearchIndexClient GetSearchIndexClient() =>
new SearchIndexClient(
Endpoint,
Serializer,
Pipeline,
ClientDiagnostics,
Version);
#endregion ctors
#region GetDocumentCount
/// <summary>
/// Retrieves a count of the number of documents in this search index.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>The number of documents in the search index.</returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
public virtual Response<long> GetDocumentCount(
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(SearchClient)}.{nameof(GetDocumentCount)}");
scope.Start();
try
{
return Protocol.Count(
cancellationToken);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
/// <summary>
/// Retrieves a count of the number of documents in this search index.
/// </summary>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>The number of documents in the search index.</returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
public virtual async Task<Response<long>> GetDocumentCountAsync(
CancellationToken cancellationToken = default)
{
using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(SearchClient)}.{nameof(GetDocumentCount)}");
scope.Start();
try
{
return await Protocol.CountAsync(
cancellationToken)
.ConfigureAwait(false);
}
catch (Exception ex)
{
scope.Failed(ex);
throw;
}
}
#endregion GetDocumentCount
#region GetDocument
/// <summary>
/// Retrieves a document from Azure Cognitive Search. This is useful
/// when a user clicks on a specific search result, and you want to
/// look up specific details about that document. You can only get one
/// document at a time. Use Search to get multiple documents in a
/// single request.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/lookup-document">Lookup Document</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="key">
/// Required. An string value that uniquely identifies each document
/// in the index. The key is sometimes referred to as a document ID.
/// See
/// <see href="https://docs.microsoft.com/rest/api/searchservice/naming-rules">Naming rules</see>
/// for the rules for constructing valid document keys.
/// </param>
/// <param name="options">
/// Options to customize the operation's behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// The document corresponding to the <paramref name="key"/>.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// The generic overloads of the <see cref="GetDocument"/> and
/// <see cref="GetDocumentAsync"/> methods support mapping of Azure
/// Search field types to .NET types via the type parameter
/// <typeparamref name="T"/>. Note that all search field types except
/// collections are nullable, so we recommend using nullable types for
/// the properties of <typeparamref name="T"/>. See
/// <see cref="GetDocumentAsync{T}(string, GetDocumentOptions, CancellationToken)"/>
/// for more information.
/// </remarks>
public virtual Response<T> GetDocument<T>(
string key,
GetDocumentOptions options = null,
CancellationToken cancellationToken = default) =>
GetDocumentInternal<T>(
key,
options,
async: false,
cancellationToken)
.EnsureCompleted();
/// <summary>
/// Retrieves a document from Azure Cognitive Search. This is useful
/// when a user clicks on a specific search result, and you want to
/// look up specific details about that document. You can only get one
/// document at a time. Use Search to get multiple documents in a
/// single request.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/lookup-document">Lookup Document</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="key">
/// Required. An string value that uniquely identifies each document
/// in the index. The key is sometimes referred to as a document ID.
/// See
/// <see href="https://docs.microsoft.com/rest/api/searchservice/naming-rules">Naming rules</see>
/// for the rules for constructing valid document keys.
/// </param>
/// <param name="options">
/// Options to customize the operation's behavior.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// The document corresponding to the <paramref name="key"/>.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// The <see cref="GetDocument"/> and <see cref="GetDocumentAsync"/>
/// methods support mapping of Azure Search field types to .NET types
/// via the type parameter <typeparamref name="T"/>. Note that all
/// search field types except collections are nullable, so we recommend
/// using nullable types for the properties of <typeparamref name="T"/>.
/// The type mapping is as follows:
/// <list type="table">
/// <listheader>
/// <term>Search field type</term>
/// <description>.NET type</description>
/// </listheader>
/// <item>
/// <term>Edm.String</term>
/// <description><see cref="String"/> (string in C# and F#)</description>
/// </item>
/// <item>
/// <term>Edm.Boolean</term>
/// <description><see cref="Nullable{Boolean}"/> (bool? in C#,\
/// Nullable<bool> in F#)</description>
/// </item>
/// <item>
/// <term>Edm.Double</term>
/// <description><see cref="Nullable{Double}"/> (double? in C#,
/// Nullable<float> in F#)</description>
/// </item>
/// <item>
/// <term>Edm.Int32</term>
/// <description><see cref="Nullable{Int32}"/> (int? in C#,
/// Nullable<int> in F#)</description>
/// </item>
/// <item>
/// <term>Edm.Int64</term>
/// <description><see cref="Nullable{Int64}"/> (long? in C#,
/// Nullable<int64> in F#)</description>
/// </item>
/// <item>
/// <term>Edm.DateTimeOffset</term>
/// <description>
/// <see cref="Nullable{DateTimeOffset}"/> (DateTimeOffset? in
/// C#, Nullable<DateTimeOffset> in F#) or
/// System.Nullable<System.DateTime> (DateTime? in C#,
/// Nullable<DateTime> in F#). Both types work, although we
/// recommend using DateTimeOffset. When retrieving documents,
/// DateTime values will always be in UTC. When indexing documents,
/// DateTime values are interpreted as follows:
/// <list type="table">
/// <item>
/// <term>UTC DateTime</term>
/// <description>Sent as-is to the index.</description>
/// </item>
/// <item>
/// <term>Local DateTime</term>
/// <description>Converted to UTC before being sent to the index.
/// </description>
/// </item>
/// <item>
/// <term>DateTime with unspecified time zone</term>
/// <description>Assumed to be UTC and sent as-is to the index.
/// </description>
/// </item>
/// </list>
/// </description>
/// </item>
/// <item>
/// <term>Edm.GeographyPoint</term>
/// <description> Azure.Core.GeoJson.GeoPoint
/// </description>
/// </item>
/// <item>
/// <term>Edm.ComplexType</term>
/// <description>
/// Any type that can be deserialized from the JSON objects in the
/// complex field. This can be a value type or a reference type, but
/// we recommend using a reference type since complex fields are
/// nullable in Azure Cognitive Search.
/// </description>
/// </item>
/// <item>
/// <term>Collection(Edm.String)</term>
/// <description><see cref="IEnumerable{String}"/> (seq<string>
/// in F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.Boolean)</term>
/// <description><see cref="IEnumerable{Boolean}"/> (seq<bool> in
/// F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.Double)</term>
/// <description><see cref="IEnumerable{Double}"/> (seq<float> in
/// F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.Int32)</term>
/// <description><see cref="IEnumerable{Int32}"/> (seq<int> in
/// F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.Int64)</term>
/// <description><see cref="IEnumerable{Int64}"/> (seq<int64> in
/// F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.DateTimeOffset)</term>
/// <description>
/// <see cref="IEnumerable{DateTimeOffset}"/> or
/// <see cref="IEnumerable{DateTime}"/> (seq<DateTimeOffset> or
/// seq<DateTime> in F#). Both types work, although we recommend
/// using <see cref="IEnumerable{DateTimeOffset}"/>. See the notes
/// above on Edm.DateTimeOffset for details.
/// </description>
/// </item>
/// <item>
/// <term>Collection(Edm.GeographyPoint)</term>
/// <description>sequence of Azure.Core.GeoJson.GeoPoint
/// (seq<GeoPoint> in F#)</description>
/// </item>
/// <item>
/// <term>Collection(Edm.ComplexType)</term>
/// <description>
/// <see cref="IEnumerable{T}"/> (seq<T> in F#) where T is any
/// type that can be deserialized from the JSON objects in the complex
/// collection field. This can be a value type or a reference type.
/// </description>
/// </item>
/// </list>
/// You can also use the dynamic <see cref="SearchDocument"/> as your
/// <typeparamref name="T"/> and we will attempt to map JSON types in
/// the response payload to .NET types. This mapping does not
/// have the benefit of precise type information from the index, so the
/// mapping is not always correct. In particular, be aware of the
/// following cases:
/// <list type="bullet">
/// <item>
/// <description>
/// Any numeric value without a decimal point will be deserialized to
/// a <see cref="Int32"/> (int in C#, int32 in F#) if it can be
/// converted or a <see cref="Int64"/> (long in C#, int64 in F#)
/// otherwise.
/// </description>
/// </item>
/// <item>
/// <description>
/// Special double-precision floating point values such as NaN and
/// Infinity will be deserialized as type <see cref="String"/> rather
/// than <see cref="Double"/>, even if they are in arrays with regular
/// floating point values.
/// </description>
/// </item>
/// <item>
/// <description>
/// Any Edm.DateTimeOffset field will be deserialized as a
/// <see cref="DateTimeOffset"/>, not <see cref="DateTime"/>.
/// </description>
/// </item>
/// <item>
/// <description>
/// Any empty JSON array will be deserialized as an array of
/// <see cref="Object"/> (object[] in C#, obj[] in F#).
/// </description>
/// </item>
/// <item>
/// <description>
/// Complex fields will be recursively deserialized into instances of
/// type <see cref="SearchDocument"/>. Similarly, complex collection
/// fields will be deserialized into arrays of such instances.
/// </description>
/// </item>
/// </list>
/// </remarks>
public virtual async Task<Response<T>> GetDocumentAsync<T>(
string key,
GetDocumentOptions options = null,
CancellationToken cancellationToken = default) =>
await GetDocumentInternal<T>(
key,
options,
async: true,
cancellationToken)
.ConfigureAwait(false);
private async Task<Response<T>> GetDocumentInternal<T>(
string key,
GetDocumentOptions options,
bool async,
CancellationToken cancellationToken)
{
if (key == null)
{ throw new ArgumentNullException(nameof(key)); }
using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(SearchClient)}.{nameof(GetDocument)}");
scope.Start();
try
{
using HttpMessage message = Protocol.CreateGetRequest(key, options?.SelectedFieldsOrNull);
if (async)
{
await Pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
Pipeline.Send(message, cancellationToken);
}
switch (message.Response.Status)
{
case 200:
{
T value = await message.Response.ContentStream.DeserializeAsync<T>(
Serializer,
async,
cancellationToken)
.ConfigureAwait(false);
return Response.FromValue(value, message.Response);
}
default:
throw new RequestFailedException(message.Response);
}
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
#endregion Get
#region Search
/// <summary>
/// Searches for documents in the search index.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/search-documents">Search Documents</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="searchText">
/// A full-text search query expression; Use "*" or omit this
/// parameter to match all documents. See
/// <see href="https://docs.microsoft.com/azure/search/query-simple-syntax">Simple query syntax in Azure Cognitive Search</see>
/// for more information about search query syntax.
/// </param>
/// <param name="options">
/// Options that allow specifying filtering, sorting, faceting, paging,
/// and other search query behaviors.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// Response containing the documents matching the query.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// <para>
/// Search and SearchAsync methods support mapping of search field
/// types to .NET types via the type parameter T. You can provide your
/// own type <typeparamref name="T"/> or use the dynamic
/// <see cref="SearchDocument"/>. See
/// <see cref="GetDocumentAsync{T}(string, GetDocumentOptions, CancellationToken)"/>
/// for more details on the type mapping.
/// </para>
/// <para>
/// Azure Cognitive Search might not be able to include all results in
/// a single response in which case <see cref="SearchResults{T}.GetResults"/>
/// will automatically continue making additional requests as you
/// enumerate through the results. You can also process the results a
/// page at a time with the <see cref="Pageable{T}.AsPages(string, int?)"/>
/// method.
/// </para>
/// </remarks>
public virtual Response<SearchResults<T>> Search<T>(
string searchText,
SearchOptions options = null,
CancellationToken cancellationToken = default) =>
SearchInternal<T>(
searchText,
options,
async: false,
cancellationToken)
.EnsureCompleted();
/// <summary>
/// Searches for documents in the search index.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/search-documents">Search Documents</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="searchText">
/// A full-text search query expression; Use "*" or omit this
/// parameter to match all documents. See
/// <see href="https://docs.microsoft.com/azure/search/query-simple-syntax">Simple query syntax in Azure Cognitive Search</see>
/// for more information about search query syntax.
/// </param>
/// <param name="options">
/// Options that allow specifying filtering, sorting, faceting, paging,
/// and other search query behaviors.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// Response containing the documents matching the query.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// <para>
/// Search and SearchAsync methods support mapping of search field
/// types to .NET types via the type parameter T. You can provide your
/// own type <typeparamref name="T"/> or use the dynamic
/// <see cref="SearchDocument"/>. See
/// <see cref="GetDocumentAsync{T}(string, GetDocumentOptions, CancellationToken)"/>
/// for more details on the type mapping.
/// </para>
/// <para>
/// Azure Cognitive Search might not be able to include all results in
/// a single response in which case
/// <see cref="SearchResults{T}.GetResultsAsync"/> will automatically
/// continue making additional requests as you enumerate through the
/// results. You can also process the results a page at a time with
/// the <see cref="AsyncPageable{T}.AsPages(string, int?)"/> method.
/// </para>
/// </remarks>
public async virtual Task<Response<SearchResults<T>>> SearchAsync<T>(
string searchText,
SearchOptions options = null,
CancellationToken cancellationToken = default) =>
await SearchInternal<T>(
searchText,
options,
async: true,
cancellationToken)
.ConfigureAwait(false);
/// <summary>
/// Searches for documents in the search index.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/search-documents">Search Documents</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="options">
/// Options that allow specifying filtering, sorting, faceting, paging,
/// and other search query behaviors.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// Response containing the documents matching the query.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// <para>
/// Search and SearchAsync methods support mapping of search field
/// types to .NET types via the type parameter T. You can provide your
/// own type <typeparamref name="T"/> or use the dynamic
/// <see cref="SearchDocument"/>. See
/// <see cref="GetDocumentAsync{T}(string, GetDocumentOptions, CancellationToken)"/>
/// for more details on the type mapping.
/// </para>
/// <para>
/// Azure Cognitive Search might not be able to include all results in
/// a single response in which case <see cref="SearchResults{T}.GetResults"/>
/// will automatically continue making additional requests as you
/// enumerate through the results. You can also process the results a
/// page at a time with the <see cref="Pageable{T}.AsPages(string, int?)"/>
/// method.
/// </para>
/// </remarks>
public virtual Response<SearchResults<T>> Search<T>(
SearchOptions options,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(options, nameof(options));
return SearchInternal<T>(
null,
options,
async: false,
cancellationToken)
.EnsureCompleted();
}
/// <summary>
/// Searches for documents in the search index.
/// <see href="https://docs.microsoft.com/rest/api/searchservice/search-documents">Search Documents</see>
/// </summary>
/// <typeparam name="T">
/// The .NET type that maps to the index schema. Instances of this type
/// can be retrieved as documents from the index.
/// </typeparam>
/// <param name="options">
/// Options that allow specifying filtering, sorting, faceting, paging,
/// and other search query behaviors.
/// </param>
/// <param name="cancellationToken">
/// Optional <see cref="CancellationToken"/> to propagate notifications
/// that the operation should be canceled.
/// </param>
/// <returns>
/// Response containing the documents matching the query.
/// </returns>
/// <exception cref="RequestFailedException">
/// Thrown when a failure is returned by the Search Service.
/// </exception>
/// <remarks>
/// <para>
/// Search and SearchAsync methods support mapping of search field
/// types to .NET types via the type parameter T. You can provide your
/// own type <typeparamref name="T"/> or use the dynamic
/// <see cref="SearchDocument"/>. See
/// <see cref="GetDocumentAsync{T}(string, GetDocumentOptions, CancellationToken)"/>
/// for more details on the type mapping.
/// </para>
/// <para>
/// Azure Cognitive Search might not be able to include all results in
/// a single response in which case
/// <see cref="SearchResults{T}.GetResultsAsync"/> will automatically
/// continue making additional requests as you enumerate through the
/// results. You can also process the results a page at a time with
/// the <see cref="AsyncPageable{T}.AsPages(string, int?)"/> method.
/// </para>
/// </remarks>
public async virtual Task<Response<SearchResults<T>>> SearchAsync<T>(
SearchOptions options,
CancellationToken cancellationToken = default)
{
Argument.AssertNotNull(options, nameof(options));
return await SearchInternal<T>(
null,
options,
async: true,
cancellationToken)
.ConfigureAwait(false);
}
private async Task<Response<SearchResults<T>>> SearchInternal<T>(
string searchText,
SearchOptions options,
bool async,
CancellationToken cancellationToken = default)
{
if (options != null && searchText != null)
{
options = options.Clone();
options.SearchText = searchText;
}
else if (options == null)
{
options = new SearchOptions() { SearchText = searchText };
}
return await SearchInternal<T>(
options,
$"{nameof(SearchClient)}.{nameof(Search)}",
async,
cancellationToken)
.ConfigureAwait(false);
}
private async Task<Response<SearchResults<T>>> SearchInternal<T>(
SearchOptions options,
string operationName,
bool async,
CancellationToken cancellationToken = default)
{
Debug.Assert(options != null);
using DiagnosticScope scope = ClientDiagnostics.CreateScope(operationName);
scope.Start();
try
{
using HttpMessage message = Protocol.CreateSearchPostRequest(options);
if (async)
{
await Pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
Pipeline.Send(message, cancellationToken);
}
switch (message.Response.Status)
{
case 200:
{
// Deserialize the results
SearchResults<T> results = await SearchResults<T>.DeserializeAsync(
message.Response.ContentStream,
Serializer,
async,
cancellationToken)
.ConfigureAwait(false);
// Cache the client and raw response so we can abstract
// away server-side paging
results.ConfigurePaging(this, message.Response);