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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333 | class AzureAISearchVectorStore(BasePydanticVectorStore):
"""
Azure AI Search vector store.
Examples:
`pip install llama-index-vector-stores-azureaisearch`
```python
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
from llama_index.vector_stores.azureaisearch import AzureAISearchVectorStore
from llama_index.vector_stores.azureaisearch import IndexManagement, MetadataIndexFieldType
# Azure AI Search setup
search_service_api_key = "YOUR-AZURE-SEARCH-SERVICE-ADMIN-KEY"
search_service_endpoint = "YOUR-AZURE-SEARCH-SERVICE-ENDPOINT"
search_service_api_version = "2024-07-01"
credential = AzureKeyCredential(search_service_api_key)
# Index name to use
index_name = "llamaindex-vector-demo"
# Use index client to demonstrate creating an index
index_client = SearchIndexClient(
endpoint=search_service_endpoint,
credential=credential,
)
metadata_fields = {
"author": "author",
"theme": ("topic", MetadataIndexFieldType.STRING),
"director": "director",
}
# Creating an Azure AI Search Vector Store
vector_store = AzureAISearchVectorStore(
search_or_index_client=index_client,
filterable_metadata_field_keys=metadata_fields,
hidden_field_keys=["embedding"],
index_name=index_name,
index_management=IndexManagement.CREATE_IF_NOT_EXISTS,
id_field_key="id",
chunk_field_key="chunk",
embedding_field_key="embedding",
embedding_dimensionality=1536,
metadata_string_field_key="metadata",
doc_id_field_key="doc_id",
language_analyzer="en.lucene",
vector_algorithm_type="exhaustiveKnn",
)
```
"""
stores_text: bool = True
flat_metadata: bool = False
_index_client: SearchIndexClient = PrivateAttr()
_index_name: Optional[str] = PrivateAttr()
_async_index_client: AsyncSearchIndexClient = PrivateAttr()
_search_client: SearchClient = PrivateAttr()
_async_search_client: AsyncSearchClient = PrivateAttr()
_embedding_dimensionality: int = PrivateAttr()
_language_analyzer: str = PrivateAttr()
_hidden_field_keys: List[str] = PrivateAttr()
_field_mapping: Dict[str, str] = PrivateAttr()
_index_management: IndexManagement = PrivateAttr()
_index_mapping: Callable[
[Dict[str, str], Dict[str, Any]], Dict[str, str]
] = PrivateAttr()
_metadata_to_index_field_map: Dict[
str, Tuple[str, MetadataIndexFieldType]
] = PrivateAttr()
_vector_profile_name: str = PrivateAttr()
_compression_type: str = PrivateAttr()
_user_agent: str = PrivateAttr()
def _normalise_metadata_to_index_fields(
self,
filterable_metadata_field_keys: Union[
List[str],
Dict[str, str],
Dict[str, Tuple[str, MetadataIndexFieldType]],
None,
] = [],
) -> Dict[str, Tuple[str, MetadataIndexFieldType]]:
index_field_spec: Dict[str, Tuple[str, MetadataIndexFieldType]] = {}
if isinstance(filterable_metadata_field_keys, List):
for field in filterable_metadata_field_keys:
# Index field name and the metadata field name are the same
# Use String as the default index field type
index_field_spec[field] = (field, MetadataIndexFieldType.STRING)
elif isinstance(filterable_metadata_field_keys, dict):
for k, v in filterable_metadata_field_keys.items():
if isinstance(v, tuple):
# Index field name and metadata field name may differ
# The index field type used is as supplied
index_field_spec[k] = v
elif isinstance(v, list):
# Handle list types as COLLECTION
index_field_spec[k] = (k, MetadataIndexFieldType.COLLECTION)
elif isinstance(v, bool):
index_field_spec[k] = (k, MetadataIndexFieldType.BOOLEAN)
elif isinstance(v, int):
index_field_spec[k] = (k, MetadataIndexFieldType.INT32)
elif isinstance(v, float):
index_field_spec[k] = (k, MetadataIndexFieldType.DOUBLE)
elif isinstance(v, str):
index_field_spec[k] = (k, MetadataIndexFieldType.STRING)
else:
# Index field name and metadata field name may differ
# Use String as the default index field type
index_field_spec[k] = (v, MetadataIndexFieldType.STRING)
return index_field_spec
def _index_exists(self, index_name: str) -> bool:
return index_name in self._index_client.list_index_names()
async def _aindex_exists(self, index_name: str) -> bool:
return index_name in [
name async for name in self._async_index_client.list_index_names()
]
def _create_index_if_not_exists(self, index_name: str) -> None:
if not self._index_exists(index_name):
logger.info(
f"Index {index_name} does not exist in Azure AI Search, creating index"
)
self._create_index(index_name)
async def _acreate_index_if_not_exists(self, index_name: str) -> None:
if not await self._aindex_exists(index_name):
logger.info(
f"Index {index_name} does not exist in Azure AI Search, creating index"
)
await self._acreate_index(index_name)
def _create_metadata_index_fields(self) -> List[Any]:
"""Create a list of index fields for storing metadata values."""
from azure.search.documents.indexes.models import SimpleField
index_fields = []
# create search fields
for v in self._metadata_to_index_field_map.values():
field_name, field_type = v
# Skip if the field is already mapped
if field_name in self._field_mapping.values():
continue
if field_type == MetadataIndexFieldType.STRING:
index_field_type = "Edm.String"
elif field_type == MetadataIndexFieldType.INT32:
index_field_type = "Edm.Int32"
elif field_type == MetadataIndexFieldType.INT64:
index_field_type = "Edm.Int64"
elif field_type == MetadataIndexFieldType.DOUBLE:
index_field_type = "Edm.Double"
elif field_type == MetadataIndexFieldType.BOOLEAN:
index_field_type = "Edm.Boolean"
elif field_type == MetadataIndexFieldType.COLLECTION:
index_field_type = "Collection(Edm.String)"
field = SimpleField(
name=field_name,
type=index_field_type,
filterable=True,
hidden=field_name in self._hidden_field_keys,
)
index_fields.append(field)
return index_fields
def _get_compressions(self) -> List[Any]:
"""Get the compressions for the vector search."""
from azure.search.documents.indexes.models import (
BinaryQuantizationCompression,
ScalarQuantizationCompression,
)
compressions = []
if self._compression_type == "binary":
compressions.append(
BinaryQuantizationCompression(compression_name="myBinaryCompression")
)
elif self._compression_type == "scalar":
compressions.append(
ScalarQuantizationCompression(compression_name="myScalarCompression")
)
return compressions
def _create_index(self, index_name: Optional[str]) -> None:
"""
Creates a default index based on the supplied index name, key field names and
metadata filtering keys.
"""
from azure.search.documents.indexes.models import (
ExhaustiveKnnAlgorithmConfiguration,
ExhaustiveKnnParameters,
HnswAlgorithmConfiguration,
HnswParameters,
SearchableField,
SearchField,
SearchFieldDataType,
SearchIndex,
SemanticConfiguration,
SemanticField,
SemanticPrioritizedFields,
SemanticSearch,
SimpleField,
VectorSearch,
VectorSearchAlgorithmKind,
VectorSearchAlgorithmMetric,
VectorSearchProfile,
)
logger.info(f"Configuring {index_name} fields for Azure AI Search")
fields = [
SimpleField(
name=self._field_mapping["id"],
type="Edm.String",
key=True,
filterable=True,
hidden=self._field_mapping["id"] in self._hidden_field_keys,
),
SearchableField(
name=self._field_mapping["chunk"],
type="Edm.String",
analyzer_name=self._language_analyzer,
hidden=self._field_mapping["chunk"] in self._hidden_field_keys,
),
SearchField(
name=self._field_mapping["embedding"],
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
searchable=True,
vector_search_dimensions=self._embedding_dimensionality,
vector_search_profile_name=self._vector_profile_name,
hidden=self._field_mapping["embedding"] in self._hidden_field_keys,
),
SimpleField(
name=self._field_mapping["metadata"],
type="Edm.String",
hidden=self._field_mapping["metadata"] in self._hidden_field_keys,
),
SimpleField(
name=self._field_mapping["doc_id"],
type="Edm.String",
filterable=True,
hidden=self._field_mapping["doc_id"] in self._hidden_field_keys,
),
]
logger.info(f"Configuring {index_name} metadata fields")
metadata_index_fields = self._create_metadata_index_fields()
fields.extend(metadata_index_fields)
logger.info(f"Configuring {index_name} vector search")
# Determine the compression type
compressions = self._get_compressions()
logger.info(
f"Configuring {index_name} vector search with {self._compression_type} compression"
)
# Configure the vector search algorithms and profiles
vector_search = VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="myHnsw",
kind=VectorSearchAlgorithmKind.HNSW,
parameters=HnswParameters(
m=4,
ef_construction=400,
ef_search=500,
metric=VectorSearchAlgorithmMetric.COSINE,
),
),
ExhaustiveKnnAlgorithmConfiguration(
name="myExhaustiveKnn",
kind=VectorSearchAlgorithmKind.EXHAUSTIVE_KNN,
parameters=ExhaustiveKnnParameters(
metric=VectorSearchAlgorithmMetric.COSINE,
),
),
],
compressions=compressions,
profiles=[
VectorSearchProfile(
name="myHnswProfile",
algorithm_configuration_name="myHnsw",
compression_name=(
compressions[0].compression_name if compressions else None
),
),
VectorSearchProfile(
name="myExhaustiveKnnProfile",
algorithm_configuration_name="myExhaustiveKnn",
compression_name=None, # Exhaustive KNN doesn't support compression at the moment
),
],
)
logger.info(f"Configuring {index_name} semantic search")
semantic_config = SemanticConfiguration(
name="mySemanticConfig",
prioritized_fields=SemanticPrioritizedFields(
content_fields=[SemanticField(field_name=self._field_mapping["chunk"])],
),
)
semantic_search = SemanticSearch(configurations=[semantic_config])
index = SearchIndex(
name=index_name,
fields=fields,
vector_search=vector_search,
semantic_search=semantic_search,
)
logger.debug(f"Creating {index_name} search index")
self._index_client.create_index(index)
async def _acreate_index(self, index_name: Optional[str]) -> None:
"""
Asynchronous version of index creation with optional compression.
Creates a default index based on the supplied index name, key field names, and metadata filtering keys.
"""
from azure.search.documents.indexes.models import (
ExhaustiveKnnAlgorithmConfiguration,
ExhaustiveKnnParameters,
HnswAlgorithmConfiguration,
HnswParameters,
SearchField,
SearchFieldDataType,
SearchIndex,
SearchableField,
SemanticConfiguration,
SemanticField,
SemanticPrioritizedFields,
SemanticSearch,
SimpleField,
VectorSearch,
VectorSearchAlgorithmKind,
VectorSearchAlgorithmMetric,
VectorSearchProfile,
)
logger.info(f"Configuring {index_name} fields for Azure AI Search")
fields = [
SimpleField(name=self._field_mapping["id"], type="Edm.String", key=True),
SearchableField(
name=self._field_mapping["chunk"],
type="Edm.String",
analyzer_name=self._language_analyzer,
hidden=self._field_mapping["chunk"] in self._hidden_field_keys,
),
SearchField(
name=self._field_mapping["embedding"],
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
searchable=True,
vector_search_dimensions=self._embedding_dimensionality,
vector_search_profile_name=self._vector_profile_name,
hidden=self._field_mapping["embedding"] in self._hidden_field_keys,
),
SimpleField(
name=self._field_mapping["metadata"],
type="Edm.String",
hidden=self._field_mapping["metadata"] in self._hidden_field_keys,
),
SimpleField(
name=self._field_mapping["doc_id"],
type="Edm.String",
filterable=True,
hidden=self._field_mapping["doc_id"] in self._hidden_field_keys,
),
]
logger.info(f"Configuring {index_name} metadata fields")
metadata_index_fields = self._create_metadata_index_fields()
fields.extend(metadata_index_fields)
# Determine the compression type
compressions = self._get_compressions()
logger.info(
f"Configuring {index_name} vector search with {self._compression_type} compression"
)
# Configure the vector search algorithms and profiles
vector_search = VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name="myHnsw",
kind=VectorSearchAlgorithmKind.HNSW,
# For more information on HNSw parameters, visit https://learn.microsoft.com//azure/search/vector-search-ranking#creating-the-hnsw-graph
parameters=HnswParameters(
m=4,
ef_construction=400,
ef_search=500,
metric=VectorSearchAlgorithmMetric.COSINE,
),
),
ExhaustiveKnnAlgorithmConfiguration(
name="myExhaustiveKnn",
kind=VectorSearchAlgorithmKind.EXHAUSTIVE_KNN,
parameters=ExhaustiveKnnParameters(
metric=VectorSearchAlgorithmMetric.COSINE,
),
),
],
compressions=compressions,
profiles=[
VectorSearchProfile(
name="myHnswProfile",
algorithm_configuration_name="myHnsw",
compression_name=(
compressions[0].compression_name if compressions else None
),
),
VectorSearchProfile(
name="myExhaustiveKnnProfile",
algorithm_configuration_name="myExhaustiveKnn",
compression_name=None, # Exhaustive KNN doesn't support compression at the moment
),
],
)
logger.info(f"Configuring {index_name} semantic search")
semantic_config = SemanticConfiguration(
name="mySemanticConfig",
prioritized_fields=SemanticPrioritizedFields(
content_fields=[SemanticField(field_name=self._field_mapping["chunk"])],
),
)
semantic_search = SemanticSearch(configurations=[semantic_config])
index = SearchIndex(
name=index_name,
fields=fields,
vector_search=vector_search,
semantic_search=semantic_search,
)
logger.debug(f"Creating {index_name} search index")
await self._async_index_client.create_index(index)
def _validate_index(self, index_name: Optional[str]) -> None:
if self._index_client and index_name and not self._index_exists(index_name):
raise ValueError(f"Validation failed, index {index_name} does not exist.")
async def _avalidate_index(self, index_name: Optional[str]) -> None:
if (
self._async_index_client
and index_name
and not await self._aindex_exists(index_name)
):
raise ValueError(f"Validation failed, index {index_name} does not exist.")
def __init__(
self,
search_or_index_client: Any,
id_field_key: str,
chunk_field_key: str,
embedding_field_key: str,
metadata_string_field_key: str,
doc_id_field_key: str,
filterable_metadata_field_keys: Optional[
Union[
List[str],
Dict[str, str],
Dict[str, Tuple[str, MetadataIndexFieldType]],
]
] = None,
hidden_field_keys: Optional[List[str]] = None,
index_name: Optional[str] = None,
index_mapping: Optional[
Callable[[Dict[str, str], Dict[str, Any]], Dict[str, str]]
] = None,
index_management: IndexManagement = IndexManagement.NO_VALIDATION,
embedding_dimensionality: int = 1536,
vector_algorithm_type: str = "exhaustiveKnn",
# If we have content in other languages, it is better to enable the language analyzer to be adjusted in searchable fields.
# https://learn.microsoft.com/en-us/azure/search/index-add-language-analyzers
language_analyzer: str = "en.lucene",
compression_type: str = "none",
user_agent: Optional[str] = None,
**kwargs: Any,
) -> None:
# ruff: noqa: E501
"""
Embeddings and documents are stored in an Azure AI Search index,
a merge or upload approach is used when adding embeddings.
When adding multiple embeddings the index is updated by this vector store
in batches of 10 documents, very large nodes may result in failure due to
the batch byte size being exceeded.
Args:
search_client (azure.search.documents.SearchClient):
Client for index to populated / queried.
id_field_key (str): Index field storing the id
chunk_field_key (str): Index field storing the node text
embedding_field_key (str): Index field storing the embedding vector
metadata_string_field_key (str):
Index field storing node metadata as a json string.
Schema is arbitrary, to filter on metadata values they must be stored
as separate fields in the index, use filterable_metadata_field_keys
to specify the metadata values that should be stored in these filterable fields
doc_id_field_key (str): Index field storing doc_id
hidden_field_keys (List[str]):
List of index fields that should be hidden from the client.
This is useful for fields that are not needed for retrieving,
but are used for similarity search, like the embedding field.
index_mapping:
Optional function with definition
(enriched_doc: Dict[str, str], metadata: Dict[str, Any]): Dict[str,str]
used to map document fields to the AI search index fields
(return value of function).
If none is specified a default mapping is provided which uses
the field keys. The keys in the enriched_doc are
["id", "chunk", "embedding", "metadata"]
The default mapping is:
- "id" to id_field_key
- "chunk" to chunk_field_key
- "embedding" to embedding_field_key
- "metadata" to metadata_field_key
*kwargs (Any): Additional keyword arguments.
Raises:
ImportError: Unable to import `azure-search-documents`
ValueError: If `search_or_index_client` is not provided
ValueError: If `index_name` is not provided and `search_or_index_client`
is of type azure.search.documents.SearchIndexClient
ValueError: If `index_name` is provided and `search_or_index_client`
is of type azure.search.documents.SearchClient
ValueError: If `create_index_if_not_exists` is true and
`search_or_index_client` is of type azure.search.documents.SearchClient
"""
import_err_msg = (
"`azure-search-documents` package not found, please run "
"`pip install azure-search-documents==11.4.0`"
)
try:
import azure.search.documents # noqa
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
except ImportError:
raise ImportError(import_err_msg)
super().__init__()
base_user_agent = "llamaindex-python"
self._user_agent = (
f"{base_user_agent} {user_agent}" if user_agent else base_user_agent
)
self._index_client: SearchIndexClient = cast(SearchIndexClient, None)
self._async_index_client: AsyncSearchIndexClient = cast(
AsyncSearchIndexClient, None
)
self._search_client: SearchClient = cast(SearchClient, None)
self._async_search_client: AsyncSearchClient = cast(AsyncSearchClient, None)
self._embedding_dimensionality = embedding_dimensionality
self._index_name = index_name
if vector_algorithm_type == "exhaustiveKnn":
self._vector_profile_name = "myExhaustiveKnnProfile"
elif vector_algorithm_type == "hnsw":
self._vector_profile_name = "myHnswProfile"
else:
raise ValueError(
"Only 'exhaustiveKnn' and 'hnsw' are supported for vector_algorithm_type"
)
self._language_analyzer = language_analyzer
self._compression_type = compression_type.lower()
# Validate search_or_index_client
if search_or_index_client is not None:
if isinstance(search_or_index_client, SearchIndexClient):
# If SearchIndexClient is supplied so must index_name
self._index_client = cast(SearchIndexClient, search_or_index_client)
self._index_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
if not index_name:
raise ValueError(
"index_name must be supplied if search_or_index_client is of "
"type azure.search.documents.SearchIndexClient"
)
self._search_client = self._index_client.get_search_client(
index_name=index_name
)
self._search_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
elif isinstance(search_or_index_client, AsyncSearchIndexClient):
# If SearchIndexClient is supplied so must index_name
self._async_index_client = cast(
AsyncSearchIndexClient, search_or_index_client
)
self._async_index_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
if not index_name:
raise ValueError(
"index_name must be supplied if search_or_index_client is of "
"type azure.search.documents.aio.SearchIndexClient"
)
self._async_search_client = self._async_index_client.get_search_client(
index_name=index_name
)
self._async_search_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
elif isinstance(search_or_index_client, SearchClient):
self._search_client = cast(SearchClient, search_or_index_client)
self._search_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
# Validate index_name
if index_name:
raise ValueError(
"index_name cannot be supplied if search_or_index_client "
"is of type azure.search.documents.SearchClient"
)
elif isinstance(search_or_index_client, AsyncSearchClient):
self._async_search_client = cast(
AsyncSearchClient, search_or_index_client
)
self._async_search_client._client._config.user_agent_policy.add_user_agent(
self._user_agent
)
# Validate index_name
if index_name:
raise ValueError(
"index_name cannot be supplied if search_or_index_client "
"is of type azure.search.documents.SearchClient"
)
if isinstance(search_or_index_client, AsyncSearchIndexClient):
if not self._async_index_client and not self._async_search_client:
raise ValueError(
"search_or_index_client must be of type "
"azure.search.documents.SearchIndexClient or "
"azure.search.documents.SearchClient"
)
if isinstance(search_or_index_client, SearchIndexClient):
if not self._index_client and not self._search_client:
raise ValueError(
"search_or_index_client must be of type "
"azure.search.documents.SearchIndexClient or "
"azure.search.documents.SearchClient"
)
else:
raise ValueError("search_or_index_client not specified")
if index_management == IndexManagement.CREATE_IF_NOT_EXISTS and not (
self._index_client or self._async_index_client
):
raise ValueError(
"index_management has value of IndexManagement.CREATE_IF_NOT_EXISTS "
"but search_or_index_client is not of type "
"azure.search.documents.SearchIndexClient or azure.search.documents.aio.SearchIndexClient "
)
self._index_management = index_management
# Default field mapping
field_mapping = {
"id": id_field_key,
"chunk": chunk_field_key,
"embedding": embedding_field_key,
"metadata": metadata_string_field_key,
"doc_id": doc_id_field_key,
}
self._field_mapping = field_mapping
self._hidden_field_keys = hidden_field_keys or []
self._index_mapping = (
self._default_index_mapping if index_mapping is None else index_mapping
)
# self._filterable_metadata_field_keys = filterable_metadata_field_keys
self._metadata_to_index_field_map = self._normalise_metadata_to_index_fields(
filterable_metadata_field_keys
)
# need to do lazy init for async client
if not isinstance(search_or_index_client, AsyncSearchIndexClient):
if self._index_management == IndexManagement.CREATE_IF_NOT_EXISTS:
if index_name:
self._create_index_if_not_exists(index_name)
if self._index_management == IndexManagement.VALIDATE_INDEX:
self._validate_index(index_name)
@property
def client(self) -> Any:
"""Get client."""
return self._search_client
@property
def aclient(self) -> Any:
"""Get async client."""
return self._async_search_client
def _default_index_mapping(
self, enriched_doc: Dict[str, str], metadata: Dict[str, Any]
) -> Dict[str, str]:
index_doc: Dict[str, str] = {}
for field in self._field_mapping:
index_doc[self._field_mapping[field]] = enriched_doc[field]
for metadata_field_name, (
index_field_name,
_,
) in self._metadata_to_index_field_map.items():
metadata_value = metadata.get(metadata_field_name)
if metadata_value:
index_doc[index_field_name] = metadata_value
return index_doc
def add(
self,
nodes: List[BaseNode],
**add_kwargs: Any,
) -> List[str]:
"""
Add nodes to index associated with the configured search client.
Args:
nodes: List[BaseNode]: nodes with embeddings
"""
from azure.search.documents import IndexDocumentsBatch
if not self._search_client:
raise ValueError("Search client not initialized")
accumulator = IndexDocumentsBatch()
documents = []
ids = []
accumulated_size = 0
max_size = DEFAULT_MAX_MB_SIZE # 16MB in bytes
max_docs = DEFAULT_MAX_BATCH_SIZE
for node in nodes:
logger.debug(f"Processing embedding: {node.node_id}")
ids.append(node.node_id)
index_document = self._create_index_document(node)
document_size = len(json.dumps(index_document).encode("utf-8"))
documents.append(index_document)
accumulated_size += document_size
accumulator.add_upload_actions(index_document)
if len(documents) >= max_docs or accumulated_size >= max_size:
logger.info(
f"Uploading batch of size {len(documents)}, "
f"current progress {len(ids)} of {len(nodes)}, "
f"accumulated size {accumulated_size / (1024 * 1024):.2f} MB"
)
self._search_client.index_documents(accumulator)
accumulator.dequeue_actions()
documents = []
accumulated_size = 0
# Upload remaining batch
if documents:
logger.info(
f"Uploading remaining batch of size {len(documents)}, "
f"current progress {len(ids)} of {len(nodes)}, "
f"accumulated size {accumulated_size / (1024 * 1024):.2f} MB"
)
self._search_client.index_documents(accumulator)
return ids
async def async_add(
self,
nodes: List[BaseNode],
**add_kwargs: Any,
) -> List[str]:
"""
Add nodes to index associated with the configured search client.
Args:
nodes: List[BaseNode]: nodes with embeddings
"""
from azure.search.documents import IndexDocumentsBatch
if not self._async_search_client:
raise ValueError("Async Search client not initialized")
if len(nodes) > 0:
if self._index_management == IndexManagement.CREATE_IF_NOT_EXISTS:
if self._index_name:
await self._acreate_index_if_not_exists(self._index_name)
if self._index_management == IndexManagement.VALIDATE_INDEX:
await self._avalidate_index(self._index_name)
accumulator = IndexDocumentsBatch()
documents = []
ids = []
accumulated_size = 0
max_size = DEFAULT_MAX_MB_SIZE # 16MB in bytes
max_docs = DEFAULT_MAX_BATCH_SIZE
for node in nodes:
logger.debug(f"Processing embedding: {node.node_id}")
ids.append(node.node_id)
index_document = self._create_index_document(node)
document_size = len(json.dumps(index_document).encode("utf-8"))
documents.append(index_document)
accumulated_size += document_size
accumulator.add_upload_actions(index_document)
if len(documents) >= max_docs or accumulated_size >= max_size:
logger.info(
f"Uploading batch of size {len(documents)}, "
f"current progress {len(ids)} of {len(nodes)}, "
f"accumulated size {accumulated_size / (1024 * 1024):.2f} MB"
)
await self._async_search_client.index_documents(accumulator)
accumulator.dequeue_actions()
documents = []
accumulated_size = 0
# Upload remaining batch
if documents:
logger.info(
f"Uploading remaining batch of size {len(documents)}, "
f"current progress {len(ids)} of {len(nodes)}, "
f"accumulated size {accumulated_size / (1024 * 1024):.2f} MB"
)
await self._async_search_client.index_documents(accumulator)
return ids
def _create_index_document(self, node: BaseNode) -> Dict[str, Any]:
"""Create AI Search index document from embedding result."""
doc: Dict[str, Any] = {}
doc["id"] = node.node_id
doc["chunk"] = node.get_content(metadata_mode=MetadataMode.NONE) or ""
doc["embedding"] = node.get_embedding()
doc["doc_id"] = node.ref_doc_id
node_metadata = node_to_metadata_dict(
node,
remove_text=True,
flat_metadata=self.flat_metadata,
)
doc["metadata"] = json.dumps(node_metadata)
return self._index_mapping(doc, node_metadata)
def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
"""
Delete documents from the AI Search Index
with doc_id_field_key field equal to ref_doc_id.
"""
if not self._index_exists(self._index_name):
return
# Locate documents to delete
filter = f'{self._field_mapping["doc_id"]} eq \'{ref_doc_id}\''
batch_size = 1000
while True:
results = self._search_client.search(
search_text="*",
filter=filter,
top=batch_size,
)
logger.debug(f"Searching with filter {filter}")
docs_to_delete = [
{"id": result[self._field_mapping["id"]]} for result in results
]
if docs_to_delete:
logger.debug(f"Deleting {len(docs_to_delete)} documents")
self._search_client.delete_documents(docs_to_delete)
else:
break
async def adelete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
"""
Delete documents from the AI Search Index
with doc_id_field_key field equal to ref_doc_id.
"""
if not await self._aindex_exists(self._index_name):
return
# Locate documents to delete
filter = f'{self._field_mapping["doc_id"]} eq \'{ref_doc_id}\''
batch_size = 1000
while True:
results = await self._async_search_client.search(
search_text="*",
filter=filter,
top=batch_size,
)
logger.debug(f"Searching with filter {filter}")
docs_to_delete = [
{"id": result[self._field_mapping["id"]]} async for result in results
]
if docs_to_delete:
logger.debug(f"Deleting {len(docs_to_delete)} documents")
await self._async_search_client.delete_documents(docs_to_delete)
else:
break
def delete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
"""
Delete documents from the AI Search Index.
"""
if node_ids is None and filters is None:
raise ValueError("Either node_ids or filters must be provided")
filter = self._build_filter_delete_query(node_ids, filters)
batch_size = 1000
while True:
results = self._search_client.search(
search_text="*",
filter=filter,
top=batch_size,
)
logger.debug(f"Searching with filter {filter}")
docs_to_delete = [
{"id": result[self._field_mapping["id"]]} for result in results
]
if docs_to_delete:
logger.debug(f"Deleting {len(docs_to_delete)} documents")
self._search_client.delete_documents(docs_to_delete)
else:
break
async def adelete_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
**delete_kwargs: Any,
) -> None:
"""
Delete documents from the AI Search Index.
"""
if node_ids is None and filters is None:
raise ValueError("Either node_ids or filters must be provided")
filter = self._build_filter_delete_query(node_ids, filters)
batch_size = 1000
while True:
results = await self._async_search_client.search(
search_text="*",
filter=filter,
top=batch_size,
)
logger.debug(f"Searching with filter {filter}")
docs_to_delete = [
{"id": result[self._field_mapping["id"]]} async for result in results
]
if docs_to_delete:
logger.debug(f"Deleting {len(docs_to_delete)} documents")
await self._async_search_client.delete_documents(docs_to_delete)
else:
break
def _build_filter_delete_query(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
) -> str:
"""Build the OData filter query for the deletion process."""
if node_ids:
return " or ".join(
[
f'{self._field_mapping["id"]} eq \'{node_id}\''
for node_id in node_ids
]
)
if filters and filters.filters:
# Find the filter with key doc_ids
doc_ids_filter = next(
(f for f in filters.filters if f.key == "doc_id"), None
)
if doc_ids_filter and doc_ids_filter.operator == FilterOperator.IN:
# use search.in to filter on multiple values
doc_ids_str = ",".join(doc_ids_filter.value)
return (
f"search.in({self._field_mapping['doc_id']}, '{doc_ids_str}', ',')"
)
return self._create_odata_filter(filters)
raise ValueError("Invalid filter configuration")
def _create_odata_filter(self, metadata_filters: MetadataFilters) -> str:
"""Generate an OData filter string using supplied metadata filters."""
odata_filter: List[str] = []
for subfilter in metadata_filters.filters:
if isinstance(subfilter, MetadataFilters):
nested_filter = self._create_odata_filter(subfilter)
odata_filter.append(f"({nested_filter})")
continue
# Join values with ' or ' to create an OR condition inside the any function
metadata_mapping = self._metadata_to_index_field_map.get(subfilter.key)
if not metadata_mapping:
raise ValueError(
f"Metadata field '{subfilter.key}' is missing a mapping to an index field, "
"provide entry in 'filterable_metadata_field_keys' for this "
"vector store"
)
index_field = metadata_mapping[0]
if subfilter.operator == FilterOperator.IN:
value_str = " or ".join(
[
f"t eq '{value}'" if isinstance(value, str) else f"t eq {value}"
for value in subfilter.value
]
)
odata_filter.append(f"{index_field}/any(t: {value_str})")
elif subfilter.operator == FilterOperator.EQ:
if isinstance(subfilter.value, str):
escaped_value = "".join(
[("''" if s == "'" else s) for s in subfilter.value]
)
odata_filter.append(f"{index_field} eq '{escaped_value}'")
else:
odata_filter.append(f"{index_field} eq {subfilter.value}")
else:
raise ValueError(f"Unsupported filter operator {subfilter.operator}")
if metadata_filters.condition == FilterCondition.AND:
odata_expr = " and ".join(odata_filter)
elif metadata_filters.condition == FilterCondition.OR:
odata_expr = " or ".join(odata_filter)
else:
raise ValueError(
f"Unsupported filter condition {metadata_filters.condition}"
)
logger.info(f"Odata filter: {odata_expr}")
return odata_expr
def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
odata_filter = None
if query.filters is not None:
odata_filter = self._create_odata_filter(query.filters)
azure_query_result_search: AzureQueryResultSearchBase = (
AzureQueryResultSearchDefault(
query, self._field_mapping, odata_filter, self._search_client
)
)
if query.mode == VectorStoreQueryMode.SPARSE:
azure_query_result_search = AzureQueryResultSearchSparse(
query, self._field_mapping, odata_filter, self._search_client
)
elif query.mode == VectorStoreQueryMode.HYBRID:
azure_query_result_search = AzureQueryResultSearchHybrid(
query, self._field_mapping, odata_filter, self._search_client
)
elif query.mode == VectorStoreQueryMode.SEMANTIC_HYBRID:
azure_query_result_search = AzureQueryResultSearchSemanticHybrid(
query, self._field_mapping, odata_filter, self._search_client
)
return azure_query_result_search.search()
async def aquery(
self, query: VectorStoreQuery, **kwargs: Any
) -> VectorStoreQueryResult:
odata_filter = None
# NOTE: users can provide odata_filters directly to the query
odata_filters = kwargs.get("odata_filters")
if odata_filters is not None:
odata_filter = odata_filter
else:
if query.filters is not None:
odata_filter = self._create_odata_filter(query.filters)
azure_query_result_search: AzureQueryResultSearchBase = (
AzureQueryResultSearchDefault(
query, self._field_mapping, odata_filter, self._async_search_client
)
)
if query.mode == VectorStoreQueryMode.SPARSE:
azure_query_result_search = AzureQueryResultSearchSparse(
query, self._field_mapping, odata_filter, self._async_search_client
)
elif query.mode == VectorStoreQueryMode.HYBRID:
azure_query_result_search = AzureQueryResultSearchHybrid(
query, self._field_mapping, odata_filter, self._async_search_client
)
elif query.mode == VectorStoreQueryMode.SEMANTIC_HYBRID:
azure_query_result_search = AzureQueryResultSearchSemanticHybrid(
query, self._field_mapping, odata_filter, self._async_search_client
)
return await azure_query_result_search.asearch()
def _build_filter_str(
self,
field_mapping: Dict[str, str],
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
) -> Optional[str]:
"""Build OData filter string from node IDs and metadata filters.
Args:
field_mapping (Dict[str, str]): Field mapping dictionary
node_ids (Optional[List[str]]): List of node IDs to filter by
filters (Optional[MetadataFilters]): Metadata filters to apply
Returns:
Optional[str]: OData filter string or None if no filters
"""
filter_str = None
if node_ids is not None:
filter_str = " or ".join(
[f"{field_mapping['id']} eq '{node_id}'" for node_id in node_ids]
)
if filters is not None:
metadata_filter = self._create_odata_filter(filters)
if filter_str is not None:
filter_str = f"({filter_str}) or ({metadata_filter})"
else:
filter_str = metadata_filter
return filter_str
def get_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
limit: Optional[int] = None,
) -> List[BaseNode]:
"""Get nodes from the Azure AI Search index.
Args:
node_ids (Optional[List[str]]): List of node IDs to retrieve.
filters (Optional[MetadataFilters]): Metadata filters to apply.
limit (Optional[int]): Maximum number of nodes to retrieve.
Returns:
List[BaseNode]: List of nodes retrieved from the index.
"""
if not self._search_client:
raise ValueError("Search client not initialized")
filter_str = self._build_filter_str(self._field_mapping, node_ids, filters)
nodes = []
batch_size = 1000 # Azure Search batch size limit
while True:
try:
search_request = create_search_request(
self._field_mapping, filter_str, batch_size, len(nodes)
)
results = self._search_client.search(**search_request)
except Exception as e:
handle_search_error(e)
break
batch_nodes = [
create_node_from_result(result, self._field_mapping)
for result in results
]
nodes, continue_fetching = process_batch_results(
batch_nodes, nodes, batch_size, limit
)
if not continue_fetching:
break
return nodes
async def aget_nodes(
self,
node_ids: Optional[List[str]] = None,
filters: Optional[MetadataFilters] = None,
limit: Optional[int] = None,
) -> List[BaseNode]:
"""Get nodes asynchronously from the Azure AI Search index.
Args:
node_ids (Optional[List[str]]): List of node IDs to retrieve.
filters (Optional[MetadataFilters]): Metadata filters to apply.
limit (Optional[int]): Maximum number of nodes to retrieve.
Returns:
List[BaseNode]: List of nodes retrieved from the index.
"""
if not self._async_search_client:
raise ValueError("Async Search client not initialized")
filter_str = self._build_filter_str(self._field_mapping, node_ids, filters)
nodes = []
batch_size = 1000 # Azure Search batch size limit
while True:
try:
search_request = create_search_request(
self._field_mapping, filter_str, batch_size, len(nodes)
)
results = await self._async_search_client.search(**search_request)
except Exception as e:
handle_search_error(e)
break
batch_nodes = []
async for result in results:
batch_nodes.append(create_node_from_result(result, self._field_mapping))
nodes, continue_fetching = process_batch_results(
batch_nodes, nodes, batch_size, limit
)
if not continue_fetching:
break
return nodes
|